2016-06-07 130 views
2
Sub amazon() 

Dim x As Long 
Dim y As Long 
Dim doc As HTMLDocument 
Dim htmTable As HTMLTable 
Dim Elements As IHTMLElementCollection 
Dim Element As IHTMLElement 
Dim bf As String 
Dim str As String 
Dim af As String 
Dim title As String 
Dim prc() 
Dim SrtTemp As Variant 
Dim i As Long, q As Long 
Dim j As Long 
Dim n As Long 
    n = Sheets("temp").Cells(Rows.Count, 5).End(xlUp).Row 
For q = 7 To n 
    Sheets("temp").Cells(q, 5) = "" 
    Sheets("temp").Cells(q, 6) = "" 
Next q 
str = "" 
    str = Sheets("temp").Cells(1, 4) 
    With CreateObject("MSXML2.XMLHTTP") 
    .Open "GET", "http://www.amazon.in/s/ref=sr_nr_n_0?fst=as%3Aoff&rh=n%3A976419031%2Cn%3A1805560031%2Ck%3A" & str & "&keywords=" & str & "&ie=UTF8&qid=1437023564&rnid=976420031", "" 
    .send 

    Do: DoEvents: Loop Until .readyState = 4 
    Set doc = New MSHTML.HTMLDocument 
    doc.body.innerHTML = .responseText 

     Set Elements = doc.getElementsByClassName("s-item-container") 
     x = Elements.Length 
     '' Debug.Print x 
     ReDim prc(0 To x) 
     z = 7 
     y = 0 
     For Each Element In Elements 
      title = Element.Children(1).innerText 
      '' Debug.Print title 
      If InStr(UCase(title), UCase(str)) Then 
        Sheets("temp").Cells(z, 5) = title 
        Price = Element.Children(2).Children(0).Children(0).innerText 
        If InStr(UCase(Price), UCase("offer")) = 0 Then 

         bf = Price 
         '' Debug.Print bf 
         prc(y) = Trim(CDbl(bf)) 
         On Error Resume Next 
         '' Debug.Print prc(y) 
         Sheets("temp").Cells(z, 6) = prc(y) 
        Else 
      '' bf = Element.Children(2).Children(3).Children(0).Children(3).innerText 
         bf = Price 
         '' Debug.Print bf 

         prc(y) = Trim(CDbl(Right(bf, 9))) 
         Sheets("temp").Cells(z, 6) = prc(y) 

         '' Debug.Print prc(y) 
        End If 
        y = y + 1 
        z = z + 1 
      End If 
     Next Element 
     Set Elements = Nothing 

     .abort 
     On Error Resume Next 
    End With 

End Sub 

當我調試我得到的錯誤運行時錯誤「91」:對象變量或帶不設置在該行標題塊變量= Element.Children(1).innerText請幫我解決這個問題。運行時錯誤「91」:對象變量或帶塊變量未設置

我在我的Excel工作表中使用亞馬遜作爲宏。我使用Excel 2016,當我調試這個宏時,我得到這個錯誤。所以請提供解決方案來解決這個問題。

如果我使用Set title = Element.Children(1).innerText,那麼我會得到Object required錯誤。

我是VBA的新手,所以請幫我解決這個問題。

回答

0

嘗試:

if not Element is nothing then 
    if not Element.Children(1) is nothing then 
     title = Element.Children(1).innerText 
    end if 
end if 
+0

雖然此代碼段可以解決的問題,[包括一個解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers )真的有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –

相關問題