1

I am new to VBA and hope someone here can help me with the following:

I would like to use VBA to open a website and then click two different buttons on this website.

My challenges with this are:
1) How can I tell the code to wait until the webpage is fully loaded so that I can make sure the button that I want to click is actually visible ?
2) How do I address the button correctly using it's unique ID ?

My code so far:

Dim varResults As New DataObject
Dim varButtonID As String
Dim i As Long
Dim objIE As Object
Dim objElement As Object
Dim objCollection As Object

varResults.SetText TxtSql.Text
varResults.PutInClipboard

' assign button ID
varButtonID = "Oracle_setExplainOptionsSpan"

' create IE object
Set objIE = CreateObject("InternetExplorer.Application")

With objIE
    .navigate "https://myURL"
    .Visible = True
End With

While objIE.ReadyState <> 4: Wend

objIE.document.getElementById(varButtonID).Click

Many thanks in advance for any help with this, Mike

Mike
  • 155
  • 3
  • 14
  • Check out http://stackoverflow.com/questions/3275515/how-to-wait-until-webbrowser-is-completely-loaded-in-vb-net – Takarii Feb 02 '17 at 11:25

2 Answers2

0

You can try to find the button by class name to click the button.

With ie.document
    Set elements = .getelementsbytagname("input")
    For Each e In elements
        If (e.getattribute("className") = "btnComment") Then
            e.Click
            Exit For
        End If
    Next e
End With

I can't think of a VBA command that waits until your page is loaded but you can enter a wait statement with a fixed time to wait.

Application.Wait(Now + #0:00:01#)
Svekke
  • 1,470
  • 1
  • 12
  • 20
  • Hi Svekke, thanks a lot for the quick reply. The Application.Wait is perfect. Can't I set the button element by ID instead of by class / tag name ? – Mike Feb 02 '17 at 10:51
  • Sure, just use "id" instead of classname, take a look at this example: https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute – Svekke Feb 02 '17 at 10:55
  • Thanks again ! If I use the ID then I don't need to loop through all other elements since this uniquely identifies the element, right ? – Mike Feb 02 '17 at 10:57
  • It loops through all elements that have the `input` tag and only clicks the buttons which have the right id. – Svekke Feb 02 '17 at 11:01
  • Thanks and sorry that I have to ask again since this is new to me. I am just wondering why I need a loop and cannot just click the specific element directly like I would do in JS etc. – Mike Feb 02 '17 at 11:05
0

I always use the Do While loop to wait until a page has loaded before continuing.

Do While IE.ReadyState <> READYSTATE_COMPLETE
Loop
Graham
  • 7,431
  • 18
  • 59
  • 84
Grenader65
  • 11
  • 2