Excel VBA刷新未按正确顺序运行的彭博数据

Excel VBA刷新未按正确顺序运行的彭博数据,excel,vba,bloomberg,Excel,Vba,Bloomberg,我的目的是更新彭博社的数据,并用不同的股票代码进行一些计算。但VBA似乎可以在不等待数据更新的情况下运行所有计算。 代码如下: Application.Calculation = xlCalculationAutomatic For i = 1 To 3 Call Worksheets("Sheet1").Range("data1").Select 'the cells "data1" contains the function =BDH(ticker, field, start d

我的目的是更新彭博社的数据,并用不同的股票代码进行一些计算。但VBA似乎可以在不等待数据更新的情况下运行所有计算。 代码如下:

Application.Calculation = xlCalculationAutomatic

For i = 1 To 3

    Call Worksheets("Sheet1").Range("data1").Select 'the cells "data1" contains the function =BDH(ticker, field, start date, end date) to get the information from Bloomberg'

    Call Application.Run("RefreshCurrentSelection")

    Worksheets("sheet1").Range("d3").Value = Worksheets("sheet1").Range("sum") 'the cells "sum" takes the sum of all BB info'     

有人知道如何修复它吗?

即使您的调用看起来很奇怪,您也应该能够利用
应用程序的值。CalculationState

还有其他方法可以“暂停”Excel,但您可以执行一个简单的While循环,除了等待
应用程序的值外,什么也不做。CalculationState
变为
xlDone

Do Until Application.CalculationState=xlDone
Loop

Bloomberg公式更新是异步的,因此您的代码不会等到更新结束。您需要将代码的其余部分安排到稍后的时间,检查数据是否已更新

它看起来是这样的:

Application.Run "RefreshCurrentSelection"
update

Sub update()
  If (check if the links have been updated) Then
    Worksheets("sheet1").Range("d3").Value = Worksheets("sheet1").Range("sum")
  Else
    Application.OnTime earliestTime:= Date + Time + timeserial(0, 0, 1), _
                   procedure:="update", Schedule:=True
  End if
End Sub

这将要求彭博API刷新数据,然后等待1秒,检查数据是否已更新,如果未更新,请再等待一秒,直到数据更新,然后它将运行范围分配。

您必须在检查和刷新之间进行拆分

Sub RefreshData()

Application.Calculation = xlCalculationAutomatic

Worksheets("Sheet1").Range("A1:A4").Select 'the cells "data1" contains the function =BDH(ticker, field, start date, end date) to get the information from Bloomberg'

Application.Run "RefreshCurrentSelection"

'Check to see if it filled
Call Check_API

End Sub

Sub Check_API()

If Application.WorksheetFunction.CountIfs(Range("A1:A4"), "#N/A Requesting Data...") > 0 Then
    'Check every 3 seconds
     Application.OnTime Now + TimeValue("00:00:03"), "Check_API"
Else

    'What to do after API filled
     Worksheets("sheet1").Range("D3").Value = Application.WorksheetFunction.Sum(Worksheets("Sheet1").Range("A1:A4")) 'the cells "sum" takes the sum of all BB info'
End If

End Sub
此外,您可以执行以下操作,而不是专注于选择:

基于默认选项设置刷新:

      Application.Run "RefreshData"
刷新当前选择:

      Application.Run "RefreshCurrentSelection"
刷新当前工作表:

      Application.Run "RefreshEntireWorksheet"
刷新当前工作簿:

      Application.Run "RefreshEntireWorkbook"
刷新所有工作簿:

      Application.Run "RefreshAllWorkbooks"

如果你感兴趣的话。更好的选择是使用VBA示例实现Bloomberg SDK中的v3 COM API类。

RefreshCurrentSelection
异步运行,因此不起作用。