1

I am very new to VBA and wrote this code. When I run it it gives me error 91. I tried fixing it by adding Set in front of a few variables but then the code wouldn't compile. Please help.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Column = Range("l:l").Column Then
    Dim IE As New InternetExplorer
    IE.Visible = False
    IE.navigate "https://www.lloydslistintelligence.com/vessel/" & Target.Value & "/overview"
    Do
        DoEvents
    Loop Until IE.readyState = READYSTATE_COMPLETE
    Dim doc As HTMLDocument
    Set doc = IE.document
    Dim sDD As String
    sDD = Trim(doc.getElementsByClassName("lli-dlist lli-dlist-shrink")    (0).innerText)
    IE.Quit
    Target.Value = sDD
    End If
End Sub
Mike J
  • 73
  • 1
  • 8
  • *Which line* triggers the error? And is it a run-time or compile-time error: question is ambiguous... – Tim Williams Jun 11 '18 at 22:12
  • 1
    Check `.length` of the `getElementsByClassName` result before trying to read element `0`. – GSerg Jun 11 '18 at 22:13
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/q/4660142/11683) – GSerg Jun 11 '18 at 22:14
  • Just a guess - you are already logged in in your browser, so you don't get the log in screen when you test manually. In your VBA session, you are not logged in – Sam Jun 11 '18 at 22:18
  • @TimWilliams the line that triggers the run-time error is `sDD = Trim(doc.getElementsByClassName("lli-dlist lli-dlist-shrink") (0).innerText)` – Mike J Jun 11 '18 at 23:37
  • If you set IE.Visible = true does the page appear as expected? – Tim Williams Jun 11 '18 at 23:39
  • @TimWilliams nope, it asks me to log in first. After I logged in, it gives the error 91 on the same line as mentioned before – Mike J Jun 11 '18 at 23:45
  • If you pause your code for a while before `Set doc = IE.document` does it then work? It may be that parts of the page are built dynamically after the initial load. – Tim Williams Jun 12 '18 at 05:18
  • Will the class name you are looking at is within an `iframe`? If so, create another IE Doc object and set that to get that iframe, then sdd will get the class from the iframe doc. – PatricK Jun 12 '18 at 06:27

0 Answers0