Narasappa
Narasappa

Reputation: 556

check if getelementsbyclassname exists in excel vba. runtime error 91 object variable or with block variable not set

All I am trying to pull data from a web page. I am looping through div with a class name from the webpage. Sometimes specific elements inside the div does not exist. that time it's showing an error runtime error 91 object variable or with block variable not set my VBA code is as below

  m = 0
  For Each htmlele1 In doc.getElementsByClassName("results")
  m = m + 1

  companyname = htmlele1.getElementsByTagName("h2")
  Address = htmlele1.getElementsByTagName("span")
   
  If Address.getAttribute("itemprop") = "Address" Then
 
   Cells(i, (m * 4 + 2)).Value = companyname.innerText + "," + Address.innerText
  End If
  
  Teliphone = htmlele1.getElementsByClassName("nolink")
  
  
  If Teliphone.getAttribute("itemprop") = "telephone" Then
  
  Cells(i, (m * 4 + 3)).Value = Teliphone.innerText

  End If
  

  no_of_property = htmlele1.getElementsByClassName("agents-stats-l")

  
If InStr(no_of_property.innerText, "Residential for sale") <> 0 Then
             Cells(i, (m * 4 + 4)).Value = Replace(no_of_property.innerText, "Residential for sale:", "")
                Else
                 Cells(i, (m * 4 + 4)).Value = 0
            End If
            Sale_price = htmlele1.getElementsByClassName("agents-stats-c")
             If InStr(Sale_price.innerText, "Avg. asking price") <> 0 Then
              Cells(i, (m * 4 + 5)).Value = Replace(Sale_price.innerText, "Avg. asking price: ", "")
              Else
                 Cells(i, (m * 4 + 5)).Value = 0
              End If

  Next

on above code snippet sometimes
** Teliphone = htmlele1.getElementsByClassName("nolink")** This is with snolink class and this doesnot exists some time and it shows error on next line.
How can I check whether element with class exists and overcome "runtime error 91 object variable or with block variable not set" this error

Upvotes: 1

Views: 2533

Answers (1)

Kostas K.
Kostas K.

Reputation: 8518

You need to set the object beforehand and check if exists before attempting to access its properties.

Set objCollection = htmlele1.getElementsByClassName("nolink")

If Not objCollection Is Nothing Then
    For Each objTeliphone In objCollection 
        'Access objTeliphone properties here
    Next
End If

Upvotes: 3

Related Questions