Am stuck and not able to proceed with this. Please find my code below. The code is basically to verify if an element is present in a webpage through VBA. I have created the below sub.
Sub ele_exist(val As String, ele As String)
Select Case val:
Case "byid":
Set verielement = doc.getElementById(ele)
If verielement Is Nothing Then
msgbox("something")
Else
msgbox("something")
End If
Case "byclass":
Set verielement = doc.getElementsByClassName(ele)
If verielement Is Nothing Then
msgbox("something")
Else
msgbox("something")
End If
Case "byname":
Set verielement = doc.getElementsByName(ele)
If verielement Is Nothing Then
msgbox("something")
Else
msgbox("something")
End If
End Select
End Sub
Now when i call this sub it gives syntax error
This is where i call the above sub
Sub start()
Set ie = New InternetExplorer
With ie
.navigate "http://www.google.com"
.Visible = True
While .Busy Or .readyState <> READYSTATE_COMPLETE
DoEvents
Wend
Set doc = .document
DoEvents
End With
***ele_exist ("byname","btnK")*** - THIS IS WHERE SYNTAX ERROR IS DISPLAYED AND THE CODE IS DISPLAYED IN RED
End Sub
I even tried converting it to a boolean FUnction rather than sub, but no luck.
Please help
As I mentione in comments, change
ele_exist ("byname","btnK")
to
ele_exist "byname","btnK"
or
Call ele_exist ("byname","btnK")
One more possible way is to use named parameters:
ele_exist val:="byname", ele:="btnK"
For additional explanation check my another post: What is the difference between entering parameters in these four different ways
Related
So I have this function that returns a value from a web page. The issue with this is that it works perfectly when I run it single step, but when I run it normally it returns another value and objIE.Quit is skipped. This is the code:
Private Function Mexico(partida As String) As String
partida = Left(partida, 8)
Set objIE = New InternetExplorer
objIE.Visible = True
objIE.navigate "http://www.siicexcaaarem.org.mx/Bases/TIGIE2007.nsf/4caa80bd19d9258006256b050078593c/$searchForm?SearchView"
Cargar
objIE.document.getElementsByName("Query")(0).Value = partida
For Each boton In objIE.document.getElementsByTagName("input")
If boton.Value = "Search" Then
boton.Click
Exit For
End If
Next
Cargar
Application.Wait Now + TimeValue("00:00:03")
Dim temp As String
Dim i As Integer
For Each t In objIE.document.getElementsByTagName("tr")
If t.className = "domino-viewentry" Then
temp = t.Children(8).innerText
End If
Next
If InStr(temp, "*") > 0 Then
temp = Left(temp, Len(temp) - 1)
End If
If InStr(temp, "%") = 0 Then
temp = temp & "%"
End If
Mexico = temp
objIE.Quit
End Function
And I am testing this with this sub:
Sub Mex()
MsgBox Mexico("33030001")
End Sub
When I run it single step, it returns "15%" with the parameter passed in the sub, while it returns just "%" when I run it normally with any given parameter. Any idea why is this happening? Any help will be appreciated.
Note: objIE is defined as a public variable, but this has not brought me any inconveniences so far, as I have other functions working properly for different websites. Also, Cargar is the usual "wait until page has loaded" instruction.
Private Sub Cargar()
Do Until objIE.Busy = False And objIE.readyState = 4
DoEvents
Loop
End Sub
You should ensure that your webpage is completely loaded before trying to grab objects off the webpage. Your line containing Application.Wait does not do this for you.
Add this sub into your module:
Sub ieBusy(ByVal ieObj As InternetExplorer)
Do While ieObj.Busy Or ieObj.readyState < 4
DoEvents
Loop
End Sub
then replace your line continaing the Application.Wait with: ieBusy objIE
So after messing with the code for hours and realizing that, sadly, the solution wasn't so simple as fixing the Cargar Load IE sub (as the page doesn't "load" as it's JavaScript driven), I found out that this was the solution:
For Each t In objIE.document.getElementsByTagName("tr")
DoEvents 'Holy fix
If t.className = "domino-viewentry" Then
temp = t.Children(8).innerText
End If
Next
I am quite unsure as why this fixed it, and came up with this while checking with msgboxes which parts of the code were not running correctly, and the msgbox inside the loop fixed it too. I'd appreciate your comments as to why this works.
I'm currently experiencing a problem with VBA. I'm trying to tick checkbox on an external website. Here is a html snippet that I'm working with:Html code from external website
I have redacted any confidential information from the snippet.
Here is my VBA code:
Set elements = objIE.document.getElementsByTagName("input")
For Each ele In elements
ele.toString
If ele.Value = "xxx" Then ele.Click
Next
So in this code the elementsvariable is an object and the loop variable ele is not being populated at all. I need to compare that the value in the check box contains value xxx. I'm not too experienced in VBA.
Any help would be appreciated
Thanks
I really don't know if that works. But in VBA the
.Value
property of a Checkbox is eighter true or false. The property of the text that is shown is:
.Caption
This code is looping properly:
Sub test()
Set objIE = CreateObject("InternetExplorer.Application")
Dim elements, ele
objIE.Visible = True
For Each ip In Sheets("Sheet1").Range("A2:A13").Value
objIE.Navigate ip
Do Until Not objIE.Busy And objIE.ReadyState = 4
DoEvents
Loop
Set elements = objIE.document.getElementsByTagName("input")
For Each ele In elements
ele.toString
If ele.Value = "xxx" Then ele.Click
Next
Next
End Sub
i can not figure this out below is the code.... I hit the error for the 2nd case to open the form frmBookingLCL.show the form name is correct. I can't figure this out. the line with the **** us the error line. HELP!!
Public Sub SendBookingEmail()
StartTime = Timer
With Session
'check first 2 letters of shipper's code, if not US raise error
If IsStartPositionCorrect(5, 14, 2, "US") <> True Or IsStartPositionCorrect(5, 2, 8, "Customer") <> True And GetDisplayText(4, 20, 1) <> "0" Then
If MsgBox("You don't appear to be in Logis ocean export US file. Please enter the file first and then run the macro.", vbOKOnly, "Export file verification....") Then
Exit Sub
End If
End If
sTypeOfMessage = "booking"
sShipmentType = Trim(.GetDisplayText(9, 61, 3))
sFileType = Trim(.GetDisplayText(4, 32, 1))
bFullVersion = False
'On Error GoTo ErrHand
'Get Outlook if it's running
Set oOutlookApp = GetObject(, "Outlook.Application")
'collect data fields for the e-mail body
GetAllLogisDataBooking
'Blow up the question form
Select Case sShipmentType
Case "FCL", "CMF", "CCS", "FPR"
frmBookingFCL.Show
Case "LCL", "GWY", "CLD"
frmBookingLCL.Show**********ERROR HERE
Case Else
frmBookingFCL.Show
'frmBookingOthers.Show
End Select
End With
Finish = Timer
TimeTook = Finish - StartTime
MyMacroStats = GetProcedureStats("Booking Confirmation", TimeTook)
Exit Sub
ErrHand:
If Err = 429 Then
MsgBox "Please note you must start Microsoft Outlook first."
End
End If
End Sub
Most likely, the error is in your user form. See the code comments.
I tried to replicate the issue below:
Sub test()
'/Sub to load the user form.
Dim x As String
x = "a"
Select Case x
Case "a", "b", "c"
UserForm1.Show '/ It Will error-out here during debugging.
End Select
End Sub
Code in UserForm1
Private Sub UserForm_Initialize()
'/ Code from : https://msdn.microsoft.com/en-us/library/office/gg251554.aspx
'/ Actually the error happens here.
Dim RetVal ' Implicitly a Variant.
' Default property is assigned to Type 8 Variant RetVal.
RetVal = CreateObject("Excel.Application")
RetVal.Visible = True ' Error occurs here.
End Sub
So going by your intialize code, either you are missing or have incorrect name for one of these controls.
frTrucker,CheckBox1,txtPickupDate. Once you correct them, the error will be gone.
I have a 'protection' sub procedure Sub unprot_manually() which can been seen below. I have another sub procedure which could be refereed to as the main procedure of the workbook. I would like to call this protection procedure prior to allowing the user to run the main procedure. With my current code below, the user is able to run the main procedure regardless of entering the correct password. Do I need to create a 'protection' function, define as Boolean, and then pass as a parameter to the main sub?
Sub unprot_manually()
Dim password_input
Dim Pass As String
Application.ScreenUpdating = False
Pass = "xxxxxx"
password_input = Application.InputBox("Password", "Awaiting User Input..")
If password_input = Pass Then
Call Unprot
'Else
'MsgBox ("Incorrect, Good Bye")
'MsgBox ("Incorrect")
End If
Application.ScreenUpdating = True
End Sub
change it from a Sub to a Function, and then check the return value.
e.g. in your main procedure,
if unprot_manually then
rest of program
else
msgbox "Incorrect Passowrd"
end if
your other section would then become:
Function unprot_manually() as Boolean
'set to fail condition until we get a success status
unprot_manually=False
...
If password_input = Pass Then
Call Unprot
'passed, so set success condition
unpot_manually=True
End If
...
End Function
Creating a UDF to do a simple string comparison is a bit OTT. You don't even need a separate procedure for this, just put the If block in your main procedure
Sub Unprot()
If Application.InputBox("Password", "Awaiting User Input..") = "xxxxxx" Then
' Rest of code here
Else
MsgBox "Incorrect Password!"
End If
End Sub
Even better than this, just set the worksheet protection with the UserInterfaceOnly option set to true, then the user can't make any changes on the front end, but your code can still run without obstruction.
UPDATE: (In response to comment)
Just use a variable and check the input:
Sub Unprot()
Dim tempStr As String
tempStr = InputBox("Password", "Awaiting User Input..") ' Assign value via input
If tempStr = vbNullString Then Exit Sub 'If no input, exit sub
If tempStr = "xxxxxx" Then
'Rest of Code
Else
MsgBox "Incorrect Password!"
End If
End Sub
I am VERY new to VBA (and know of it only within excel).
I am trying to cycle through some (but not all) checkboxes. They are currently named CheckBox1 through CheckBox15. Howe do I cycle through say for instance CheckBox5 through CheckBox10?
I guess I am hoping there is a 'method' similar to 'CheckType' for controls that will allow me to check name?
Here is what I have tried. Causes a Compile Error - Sub or Function not defined, and highlights Worksheet.
Private Sub BoxCheck()
atLeastOneChecked = False
For i = 2 To 4
If Worksheets("ActiveX").Controls("Checkbox" & i).Value = True Then
atLeastOneChecked = True
End If
Next i
End Sub
While the above doesnt work, what is below does:
Private Sub BoxCheck()
atLeastOneChecked = False
For i = 1 To 2
If Sheet2.CheckBox2.Value = True Then
atLeastOneChecked = True
End If
Next i
End Sub
Of course, the loop has no affect on the outcome, but it compiles and atLeastOneChecked turns from False to True when Checkbox2 is True. Note that Sheet2 has been named ActiveX. I clearly don't understand how Worksheet and Controls work. Could someone help?
After fixing the error described below, this still won't work. I simplified to the following:
Private Sub BoxCheck()
Dim ole As OLEObject
atLeastOneChecked = False
Set ole = Sheets("ActiveX").OLEObjects("Checkbox2")
If ole.Value = True Then
atLeastOneChecked = True
End If
End Sub
This doesn't work. It fails at:
If ole.Value = True Then
The error states: Object Doesn't support this property or method
This is true for OLEObjects, but not for Checkboxes. When I look at the properties of ole, I see that its Object property is set to Object/Checkbox and that this Object has a value. I guess that is what I should be referencing in my if statement, but I don't know how.
I think I solved the problem.
The value of the Checkbox is accessed by Referencing the Object property within the OLEObject I set...Like this:
If ole.Object.Value = True Then
Thanks for all your help. If someone has a more elegant solution, I would still like to see it.
Use CheckBox.Name
Example:
For Each cb In ActiveSheet.CheckBoxes
If cb.Name = "CheckBox5"
' Do stuff
End If
Next cb
To expand on #Parker's answer:
Private Sub BoxCheck()
atleastonechecked = False
Dim oles As OLEObject
For i = 2 To 4
'If you're using Shapes Controls:
If ThisWorkbook.Worksheets("ActiveX").Shapes("Check Box " & i).Value = True Then
atleastonechecked = True
End If
' If you're using ActiveX Controls
Set oles = ThisWorkbook.Worksheets("ActiveX").OLEObjects("CheckBox" & i)
If oles.Value = True Then
atleastonechecked = True
End If
Next i
End Sub
Sorry, just put together the previous answer without testing - that always fails. Just use the If loop based on what type of control you're using.