Sam
Sam

Reputation: 65

Check with VBA if an element exists on the page

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

Upvotes: 2

Views: 29708

Answers (4)

Tom K.
Tom K.

Reputation: 41

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

Upvotes: 4

Steven Alpha
Steven Alpha

Reputation: 187

Thanks for the solution. I used as follows,

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

Upvotes: 3

Sunita Jaiswal
Sunita Jaiswal

Reputation: 46

Ryan's answer is the correct.

set Element = document.getelementbyID("result_0")

Upvotes: 3

Lukas
Lukas

Reputation: 1

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

Upvotes: 0

Related Questions