Check with VBA if an element exists on the page

青春壹個敷衍的年華 提交于 2020-02-02 15:12:25

问题


I have 15,000 products and I need to know if they're X, Y or Z. The code below checks on amazon to see if a product is a type of XYZ.

God help me, it actually works. The only exception is when it searches a product no longer sold by Amazon. Then the element ID that I'm looking for which contains the product description that I'm searching doesn't exist on the page, and the code breaks on line

text = document.getelementbyID("result_0").innertext

with the error "Object variable or With block variable not set".

How do I check if the element exists before proceeding with the rest of the code?

Thanks!

Sam

Sub LetsAutomateIE()

Dim barcode As String
Dim rowe As Integer
Dim document As HTMLDocument
Set ie = CreateObject("InternetExplorer.Application")
Dim Element As HTMLDivElement
Dim text As String
Dim pos As Integer

rowe = 2

While Not IsEmpty(Cells(rowe, 2))

barcode = Cells(rowe, "B").Value

With ie
.Visible = False
.navigate2 "https://www.amazon.co.uk/s/ref=nb_sb_noss_1?url=search-    
alias%3Daps&field-keywords=" & barcode
Do Until ie.readyState = 4
Loop
End With

Set document = ie.document

text = document.getElementById("result_0").innerText

If InStr(text, "X") Or InStr(text, "Y") Or InStr(text,     
"Z") <> 0 Then pos = 1

If pos <> 0 Then Cells(rowe, 4) = "Y" Else Cells(rowe, 4) = "N"

rowe = rowe + 1

Wend

Set ie = Nothing

End Sub

回答1:


Ryan's answer is the correct.

set Element = document.getelementbyID("result_0")




回答2:


Thanks for the solution. I used as follows,

If IsObject(objIE.document.getElementById("e164NumberMask")) Then
    'do true stuff
Else
    'do false stuff
End If



回答3:


Posting an alternative in case top answer is not working for other people:

I was still getting run time error '91' after checking with IsObject()

IsObject() works fine if ObjIE is an InternetExplorer object but I was using an InternetExplorerMedium object and had to validate with this instead since it was returning a nothing object:

If Not objIE.document.getElementById("e164NumberMask") Is Nothing Then
    'do true stuff
Else
    'do false stuff
End If



回答4:


You can try something like this.

Function objectHandler(objID)

Dim TestObj As Object

On Error GoTo Handler:

Set TestObj = ObjIE.document.getElementById(objID)
objectHandler = True
Exit Function

Handler:
objectHandler = False

End Function


来源:https://stackoverflow.com/questions/39352270/check-with-vba-if-an-element-exists-on-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!