Checking if element exists VBA Selenium - vba

Looking for help on how to implement VBA code to check if an element exists or explicitly waiting for it in VBA. Here is a small sample code I am testing out. The below code gives an error while running since it says "Object Required"
Dim Driver As New ChromeDriver
Driver.get "Test website"
If Driver.IsElementPresent(By.XPath("/html/body/div[2]/div/div[5]/h3"))) Then
Debug.Print("Yes")
Else
Debug.Print("No")
I even have tried changing the .IsElementPresent to this line of code so I can test the size of the element if it exists but receiving an error that "NoSuchElementError"
Debug.Print (browser.FindElementByXPath("/html/body/div[2]/div/div[5]/h3").Size())

Seem to work for me. The only issue I am seeing in your code is that you didn't declare By anywhere.
e.Start isn't a requirement, but I do it anyway.
So I would try declaring By and see what happen there. And you need to set it as a new instance, a simply type-declaration won't work, which means:
Just using Dim By As Selenium.By is NOT enough, but either of these lines:
Dim By As New Selenium.By
or
Dim By As Selenium.By
Set By = New Selenium.By
The Object Required error you are receiving is likely due to the missing declaration I stated above.

As text above, for me it worked like this...
Dim ch As Selenium.ChromeDriver
Set ch = New Selenium.ChromeDriver
'... all code ...
If ch.IsElementPresent(FindBy.XPath("//*[#id='div_footer']/table/tbody/tr/div")) Then
ch.FindElement(FindBy.XPath("//*[#id='div_footer']/table/tbody/tr/div")).Click
ElseIf ch.IsElementPresent(FindBy.XPath("//*[#id='xlsbutton']")) Then
ch.FindElement(FindBy.XPath("//*[#id='xlsbutton']")).Click
Else
'nohing here, only to understand stament
boolean_check_Download_Click_XYZ = false
End If

Related

Run time error '424' Object Required in Selenium VBA for Edge Browser

On executing below code, system throws error
Run Time Error '424'
Object Required
Through the code, I am extracting data from a website (using Edge browser).
If match is found, a link appears on the portal from which data can be downloaded whose Xpath is "//*[#id='downloadReport']/div"
If link is present, the link should be clicked using code
Obj.FindElementByXPath("//*[#id='downloadReport']/div").Click
Else if no match is found, the above code should be skipped as Xpath as above is not available and another macro execution should be called using
Call EdgeAutoTest2
I am new to coding
Please help me in resolving this error.
Sub EdgeAutoTest1()
Set Obj = New selenium.EdgeDriver
Obj.SetCapability "ms:edgeOptions", "{""excludeSwitches"":[""enable-automation""]}"
Obj.Start "edge", ""
Obj.Get "https://***website*****"
Obj.Window.Maximize
Obj.FindElementByName("croreAccount").SendKeys ("Search")
Obj.FindElementByXPath("//*[#id='loadSuitFiledDataSearchAction']/div[1]/div[3]/div[4]/img").Click
Obj.FindElementById("borrowerName").SendKeys (ThisWorkbook.Sheets("Sheet1").Range("C5").Value)
Obj.FindElementByXPath("//*[#id='search-button']/ul/li[1]/div/input").Click
Obj.Wait 20000
Obj.FindElementByXPath("//*[#id='three-icons']/ul/li[3]/a/div").Click
Obj.Wait 20000
If Obj.IsElementPresent(By.XPath("//*[#id='downloadReport']/div")) = True Then **'error occurs here*****
Obj.FindElementByXPath("//*[#id='downloadReport']/div").Click
Else
Obj.Wait 100
End If
Call EdgeAutoTest2
End Sub
The only issue in your code is you are missing is that you didn't define By.
As you are using:
If Obj.IsElementPresent(By.XPath("//*[#id='downloadReport']/div")) = True Then
You need to:
Dim By As New Selenium.By

Creating a new IUI Automation Handler object in order to subscribe to an automation event

So, here it goes. To start, A disclaimer, I understand that MS Access is not built for this kind of work. It is my only option at this time.
I have done just a bit of Automation using UIAutomationClient and I have successfully used its other features, however I cannot for the life of me get it to subscribe to events.
Normally, it is supposed to be a bit like this:
Dim CUI as new CUIAutomation
Dim FocusHandler as IUIAutomationFocusChangedEventHandler
Set FocusHandler = new IUIAutomationFocusChangedEventHandler(onFocusChanged)
C.AddFocusChangedEventHandler(Element,TreeScope_Children, null, FocusHandler)
end function
'
'
Function onFocusChanged(src as Object, args as AutomationEventArgs)
''my code here
end function
Yet when I attempt this, I get the error "expected end of statement" on the line:
FocusHandler = new IUIAutomationFocusChangedEventHandler(onFocusChanged)
additionally, if I leave off the (onFocusChanged) I get the error "Invalid use of new Keyword".
It seems like I am missing a reference somewhere. The usual drop down when using "new" does not contain the IUI handler classes though they are in the object library.
I am not sure if there is just some piece I am not accounting for in the code since I am using vba, but all examples seem to be for .net or C#/C++. Any help would be appreciated.
Additionally, I have no problem finding the element in question and all other pieces work fine. If you need any other pieces of the code let me know.
Edit: added set to line 3. No change in the problem though.
After two years this probably isn't relevant any more, but perhaps somebody else encounters this problem... The answer is to create a new class that implements the HandleAutomationEvent method.
Here I created a class named clsInvokeEventHandler and (importantly) set the Instancing property to PublicNotCreatable:
Option Explicit
Implements IUIAutomationEventHandler
Private Sub IUIAutomationEventHandler_HandleAutomationEvent(ByVal sender As UIAutomationClient.IUIAutomationElement, ByVal eventId As Long)
Debug.Print sender.CurrentName
End Sub
And to use it:
Sub StartInvokeHandler()
Dim oUIA As New CUIAutomation8
Dim oRoot As IUIAutomationElement
Dim InvokeHandler As clsInvokeEventHandler
Set InvokeHandler = New clsInvokeEventHandler
Set oRoot = oUIA.GetRootElement
oUIA.AddAutomationEventHandler UIA_Invoke_InvokedEventId, oRoot, TreeScope_Descendants, Nothing, InvokeHandler
End Sub

Getting A NullRefrenceException And Cannot Find Out Why?

My goal here is to create a web browser that has a tab system in VB. Since I cannot explicitly name every single new tab the user will use, I have to make more generalized callings. Here's the conflicting code (my btnGo):
Dim thisBrowser As newWebBrowser = Me.tabBrowser.SelectedTab.Tag
If txtAdressSearch.Text.Contains(".com") Or txtAdressSearch.Text.Contains(".net") Or txtAdressSearch.Text.Contains(".gov") Or txtAdressSearch.Text.Contains(".edu") Or txtAdressSearch.Text.Contains(".org") Then 'More to be checked for
thisBrowser.Navigate(txtAdressSearch.Text)
Else
thisBrowser.Navigate("https://www.google.com/search?sourceid=chrome-psyapi2&rlz=1C1ASAA_enUS445&ion=1&espv=2&ie=UTF-8&q=" + txtAdressSearch.Text)
End If
And here's the newWebBrowser code:
Public Class newWebBrowser
Inherits WebBrowser
Private Sub webBrowserComplete() Handles Me.DocumentCompleted
Dim newTab As TabPage = frmBrowser.Tag()
Dim frmSK As New frmBrowser
Dim hi As String
newTab.Text = Me.DocumentTitle
frmSK.txtAdressSearch.Text = Me.Url.ToString
End Sub
End Class
Any time I enter something into txtAdressSearch, Visual Studio raises a NullRefrenceException and highlights thisBrowser.Navigate(txtAdressSearch.Text). As a side note, it says "Object reference not set to an instance of an object."
Anyone know whats the problem here? Thank you.
After debugging for more than an hour, I looked over my code and saw I was missing a big part of it. I wrote it all in and it worked fine. The issue was the tags weren't being defined correctly (and in some cases, not at all) so .Tag was returning Nothing.
Thanks to all who helped.

DataGrid information throwing out 'Object Reference' error.

So. I looked around Stackoverflow before posting this question. I found other Questions, but none of them answered my question.
This is my code:
Sub getData()
ListBox1.Items.Clear()
Dim rowindex As String
Dim found As Boolean = False
Dim actie As String
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells.Item("Column1").Value.ToString.Contains("2014-0" & Date.Today.Month.ToString) Then
rowindex = row.Index.ToString()
found = True
actie = row.Cells("Column2").Value.ToString()
ListBox1.Items.Add(actie)
End If
Next
If Not found Then
MsgBox("Item not found")
End If
End Sub
What this does is calls data from a DataGrid. The issue I am having is on 'ListBox1.items.add(actie)'. If I use a Message Box it works fine until I get to the last one and then it also throws the error. (That'll likely be why it throws the error straight away for the ListBox as it adds them all 'at the same time'). I've tried an 'ELSE' but with the else it just says no data found. I thought a Do Until might have worked but it did not.
Error I am getting is: Object Reference Not Set to an Instance of an Object.
I assume this is going to be something really basic and I'm going to hit myself when I turns out to be extremely basic.

VBA runtime error 91 even though variable is set

I am struggling with a piece of code that places a custom class in a collection. Every time I run the code I get a runtime error 91. The error is occuring on the Set pjt = New CProject line.
Dim Projects As Collection
Private Sub BuildProjects()
Dim pjt As CProject
Set Projects = New Collection
Set pjt = New CProject '<-----ERROR OCCURS HERE
'Do some other stuff
End Sub
This is obviously the simplest form of the Sub, but it still throws the error! What am I doing wrong? Do I need to set the access for the CProject class file somehow?
All your help will be greatly appreciated.
The line Set pjt = New CProject is calling the constructor for CProject.
The error will most likely be in the constructor of CProject.
Error 91 is a null reference