2016-11-12 219 views
0

我已經嘗試了大量教程,並花費了大量時間嘗試解決此問題,但無法完全找到答案。VBA Excel 2010運行時錯誤'91'對象變量或With Block變量未設置

我是新來的VBA與excel,並一直試圖獲得一個自動化的網絡搜索到Excel中,從一列單元格中獲取查詢並將結果中的元素寫入另一行單元格。爲了保持這個例子的簡單,我使用了Google搜索。

我總是最後使用相同的消息:

運行時error'91' 對象變量或帶塊變量未設置

error screenshot

這裏是代碼的最新版本:

Sub Macro1() 

Dim ie As Object 
Set Rng = Range("A3:A5") 

Set Row = Range(Rng.Offset(1, 0), Rng.Offset(1, 0).End(xlDown)) 

Set ie = CreateObject("InternetExplorer.Application") 
With ie 
    .Visible = True 
    For Each Row In Rng 
    .navigate "https://www.google.com/#q=" & Range("A" & Row.Row).Value 

Do 
    DoEvents 
     Loop Until ie.readyState = READYSTATE_COMPLETE 

     Dim doc As HTMLDocument 
     Set doc = ie.document 
     While ie.readyState <> 4 

Wend 

Range("B" & Row.Row) = doc.getElementById("resultStats" & Range("A" & Row.Row).Value).innerText 

Next Row 

ie.Quit 

End With 

End Sub 

任何幫助,非常感謝。

感謝,

+0

好像'doc.getElementById( 「resultStats」 &範圍( 「A」 &Row.Row)。價值)'或'範圍( 「A」 &Row.Row)'可能的計算結果爲'Null' 。你能確認'Range(「A」&Row.Row)'實際返回一個非空值,並且HTML文檔中有一個實際名爲「resultStatsA?」的元素。 – InfectedPacket

+0

如何使用正確的縮進,以便您可以看到哪些代碼行打開一個塊並關閉它?它會使您的代碼更易於閱讀和排除故障。 – teylyn

回答

0

它不工作的原因,是因爲有一個名爲「resultStats YOURVALUEHERE」在谷歌的ID沒有元素。 getElementById("resultStats")將返回結果的量,例如,如果您在Google上搜索VBA,則會獲得36,100,000個結果。
此外,您應該使用Option Explicit

如果你想返回「Header」和「URL」,你可以這樣做。但是,A3中只能有1個值 - 但這當然可以修改。

Option Explicit 

Sub Macro1() 
Dim rng As Range, Cell As Range 
Dim i As Integer 
Dim IE As Object, objDiv As Object, objH3 As Object, objLink As Object 
Dim strText As String 

Set rng = Range("A3:A5") 

Set Cell = Range(rng.Offset(1, 0), rng.Offset(1, 0).End(xlDown)) 

Set IE = CreateObject("InternetExplorer.Application") 

    With IE 
     .Visible = False ' Change to True if you want to open IE and have it visible 

     For Each Cell In rng 
     .navigate "https://www.google.com/#q=" & Range("A" & Cell.row).value 

     Do 
      DoEvents 
       Loop Until IE.readyState = READYSTATE_COMPLETE 

       Dim doc As HTMLDocument 
       Set doc = IE.document 
       While IE.readyState <> 4 
     Wend 

      ' Add the 5 first results to rows 
      For i = 0 To 4 
       Set objDiv = doc.getElementById("rso") 
       Set objH3 = objDiv.getElementsByTagName("H3")(i) 
       Set objLink = objH3.getElementsByTagName("a")(0) 

       strText = Replace(objLink.innerHTML, "<EM>", "") 
       strText = Replace(strText, "</EM>", "") 

       Dim CellRow As Integer 
       If i = 0 Then 
        CellRow = Cell.row 
       Else 
        CellRow = CellRow + 1 
       End If 

       ' Insert values starting in B3 and C3 and continue with B4, C4, for the next value etc. 
       Cells(CellRow, 2) = strText 
       Cells(CellRow, 3) = objLink.href 
      Next i 

     Next Cell 

    IE.Quit 

    End With 
End Sub 
相關問題