2015-11-11 36 views
1

我的目的是更新彭博数据并用不同的代号进行一些计算。但似乎VBA将运行所有计算而不等待数据更新。 下面是代码: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'  

任何人都知道如何解决它,好吗?非常感谢你!

回答

0

即使您的呼叫看起来很奇怪,您应该可以使用Application.CalculationState中的值。

还有其他的方法来“暂停”的Excel,但你可以做一个简单的while循环束手无策,除了等待Application.CalculationState值变为xlDone

Do Until Application.CalculationState=xlDone 
Loop 
+0

'RefreshCurrentSelection'异步运行,所以不起作用。 – assylias

0

彭博公式更新是异步的,所以你的代码不会等到更新结束。您需要稍后安排其余代码,检查数据是否已更新。

它应该是这样的:

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秒,检查是否更新数据,再等第二,如果没有等等,直到数据被更新,然后它会运行范围分配。

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" 

刷新所有工作簿:

​​3210

如果你有兴趣。还有更好的选择是实现v3 COM API类,可以在彭博的SDK中找到VBA示例。