使用 Excel 2010与VBA 7.0
this video中的代码一直有效,直到我到达10:01。执行行
时 Dim Resp As String: Resp = Http.ResponseText
我得到Runtime error 91 Object variable or With block variable not set
。
问题:如何解决此错误消息?
Private Sub btnRefresh_Click()
Dim W As Worksheet: Set W = ActiveSheet
Dim Last As Integer: Last = W.Range("A100").End(xlUp).Row
Dim Symbols As String
Dim i As Integer
Dim URL As String
Dim Http As WinHttpRequest
If Last = 1 Then Exit Sub
For i = 2 To Last
Symbols = Symbols & W.Range("A" & i).Value & "+"
Next i
Symbols = Left(Symbols, Len(Symbols) - 1)
URL = "http://finance.yahoo.com/d/quotes.csv?s=" & Symbols & "&f=snl1hg"
Http = New WinHttpRequest
Http.Open "GET", URL, False
Http.Send
Dim Resp As String: Resp = Http.ResponseText
Debug.Print Symbols
Debug.Print URL
End Sub
答案 0 :(得分:2)
解决此问题的两种方法。
1)设置对Microsoft WinHttp 5.1库的引用(VBA中的Tools-> References工具栏)并修复以下代码行:
更改
Dim Http As WinHttpRequest 'Incorrect
Dim Http As New WinHttpRequest 'Correct
删除
Http = New WinHttpRequest 'Incorrect
2)您也可以使用单独的对象来完成此操作,这样就无需在VBA中设置库引用:
Private Sub btnRefresh_Click()
Dim W As Worksheet: Set W = ActiveSheet
Dim Last As Integer: Last = W.Range("A100").End(xlUp).Row
Dim Symbols As String
Dim i As Integer
Dim URL As String
If Last = 1 Then Exit Sub
For i = 2 To Last
Symbols = Symbols & W.Range("A" & i).Value & "+"
Next i
Symbols = Left(Symbols, Len(Symbols) - 1)
URL = "http://finance.yahoo.com/d/quotes.csv?s=" & Symbols & "&f=snl1hg"
' Create object here
Dim HTTP As Object
Set HTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
HTTP.Open "GET", URL
HTTP.Send
'Test Response
MsgBox HTTP.ResponseText
End Sub