I am bumped in a situation where I need to do something if an element exists, and if that element does not exists I will need to skip to the rest of the code. I have tried several methods but I do not know why it does not work, the code looks logical to me and it worked for similar macros. Code below:
Do
DoEvents
Loop Until driver.ExecuteScript("document.readystate") <> "complete"
If driver.FindElementByName("x").IsPresent Then
Item.Offset(0, 2).Value = "Completed already" 'And need to skip to next iteration
ElseIf driver.FindElementByName("x") Is Nothing Then
Set cancel= driver.FindElementByName("cancelbutton")
cancel.Click
Set myVar= Item.Offset(0, 1)
Set radiobtn = driver.FindElementByXPath("//input[@value='" & myVar & "']")
radiobtn.Click
Set cancelSelected = driver.FindElementByName("submitCancel")
cancelSelected.Click
driver.SwitchToAlert.Accept
Item.Offset(0, 2).Value = "Canceled"
driver.Refresh
driver.Wait 1000
End If
I have also tried the situation where if the element X is present, then find other element
If driver.FindElementByName("x").IsPresent Then
Item.Offset(0, 2).Value = "Completed already"
ElseIf driver.FindElementByName("Y").IsPresent Then
Set cancel= driver.FindElementByName("cancelbutton")
cancel.Click
Set myVar= Item.Offset(0, 1)
Set radiobtn = driver.FindElementByXPath("//input[@value='" & myVar & "']")
radiobtn.Click
Set cancelSelected = driver.FindElementByName("submitCancel")
cancelSelected.Click
driver.SwitchToAlert.Accept
Item.Offset(0, 2).Value = "Canceled"
driver.Refresh
driver.Wait 1000
End If
When element X is present on the page element Y is not, and vice versa. I have also tried .count > 0
but it still does not work. Could anyone help me with a solution or give me some tips and trick?
Actually, I bought a course on Udemy and found the answer myself. There are several ways to find if an element is present and what to do next if it is or not present. Funny, the solution is so simple that I'm embarrassed I missed it.
First Dim By AS New By
Then add a split second of wait before and after the if clause:
driver.Wait 500
If driver.IsElementPresent(By.Name("uncompleteButton__")) Then
Item.Offset(0, 2).Value = "Can't do stuff, go to next iteration."
Else
Set cancelitemsbtn = driver.FindElementByName("cancelButton")
cancelitemsbtn.Click
Item.Offset(0, 2).Value = "Can do stuff"
driver.Wait 500
End if