2017-03-01 49 views
1

我的代碼是從網站獲取信息,但在某些情況下,該信息的HTML代碼,只是不存在,所以我用On Error來處理它。如您在代碼中看到的,我正在瀏覽列表並獲取每行(大約700行)的信息。起初,錯誤發生在第10行,然後我添加了On Error GoTo 0。之後,它開始在第13行拋出。上的錯誤不能與IE瀏覽器自動化工作

我的配置已經設置爲關於Unhandeled Errors的破解。

的運行時錯誤號碼爲:

91:對象未設置變量或With塊變量。

它在線路之間發生的「**」

Sub GetData_DK() 

    Dim IE As New InternetExplorer 
    Dim URL As String 
    Dim doc As HTMLDocument 'variable for document or data which need to be extracted out of webpage 
    Dim onl As String 
    Dim sto As String 
    Dim pri As String 
    FinalRow = tme.Cells(Rows.Count, "G").End(xlUp).Row 

    Dim hyper As Workbook 
    Set hyper = Workbooks.Open("path") 
    FinalRowH = hyper.Sheets("tme").Cells(Rows.Count, "A").End(xlUp).Row 
    ThisWorkbook.Activate 

    For a = 5 To FinalRow 

     onl = "" 
     sto = "" 
     pri = "" 

     For b = 5 To FinalRowH 
      If (ThisWorkbook.Sheets("tme").Cells(a, 7).Value = hyper.Sheets("tme").Cells(b, 1).Value) Then 
       URL = hyper.Sheets("tme").Cells(b, 3).Value 
       Exit For 
      End If 
     Next b 

     IE.navigate URL 
     IE.Visible = True 

     Do 
      If IE.readyState = READYSTATE_COMPLETE Then 
       If IE.document.readyState = "complete" Then Exit Do 
      End If 
      Application.Wait DateAdd("s", 1, Now) 
     Loop 
     'Application.Wait (Now() + TimeValue("00:00:006")) ' For internal page refresh or loading 


     Set doc = IE.document 

     On Error Resume Next 
     'gets HTLM class containing the value 
     **onl = CStr(doc.getElementsByClassName("items-in-stock align-left")(0).innerText)** 
     On Error GoTo 0 
     If (onl = Chr(160) Or onl = " " Or onl = " " Or onl = "" Or onl = vbNullString Or Left(onl, 9) = "Forventet") Then 
      Cells(a, 8).Value = 0 
     Else 
      Cells(a, 8).Value = 1 
     End If 

     On Error GoTo price 
     'repeats the process for stores 
     sto = CStr(doc.getElementsByClassName("open-cas-tab")(0).innerText) 
     sto = Left(sto, InStr(sto, " ") - 1) 
     Cells(a, 9).Value = sto 

price: 
     On Error GoTo 0 

     On Error Resume Next 
     'repeats the process for price 
     pri = CInt(CStr(doc.getElementsByClassName("product-price-container")(0).innerText)) 
     Cells(a, 10).Value = pri 
     On Error GoTo 0 
    Next a 
End Sub 

請讓我知道我做錯了什麼(:

回答

1

如果沒有的元素是通過使用getElementsByClassName返回那麼您可以測試length屬性,它將爲0.如果嘗試訪問第0個元素時嘗試跳過生成的錯誤,因爲您認爲會得到肯定的結果,所以最好選擇此項。

所以你可以試試這個:

Set doc = IE.document 

Dim objElements As Object 
Set objElements = doc.getElementsByClassName("items-in-stock align-left") 

If objElements.length > 0 Then 
    ' some elements are returned - get the text from the first one 
    onl = CStr(objElements(0).innerText) 
Else 
    ' nothing returned - lets handle it gracefully with no error 
    MsgBox "No elements with that class!" 
    '... prepare to exit 
End If 

' do stuff with onl 
+0

這是brillaint!感謝分享你的知識,羅賓(: –

相關問題