The error I'm getting is "Object variable or With Block Variable not set " in reference to the ".click" line of the code. I'm newer to VBA coding and I've tried various different things but I'm unable to figure it out. Any ideas?
The point of the code is to launch a new internet explorer, navigate to a work site, click on a drop down, tab once, then click enter. Ideally I'd like to just click the 'ok' button but I'm getting same error so I'll probably switch it if you guys can tell me what I'm doing wrong to get the error.
Sub GetData()
Dim objIE As InternetExplorer
Dim Ele As Object
Set IE = New InternetExplorer
IE.Visible = True
IE.navigate "http://workurl"
Do While IE.Busy = True Or IE.readyState <> 4: DoEvents: Loop
IE.document.getElementsByName("staffGroupCombo")(0).Click
Application.Wait (Now() + TimeValue("00:00:01"))
SendKeys "+{TAB}"
Application.Wait (Now() + TimeValue("00:00:01"))
SendKeys "+{~}"
'Just placeholder stuff I sometimes need to copy
'Do While IE.Busy = True Or IE.readyState <> 4: DoEvents: Loop
'Debug.Print ele.ClassName
'Debug.Print ele.tagName
'Debug.Print ele.ID
Sometimes constructs in a single line like
IE.document.getElementsByName("staffGroupCombo")(0).Click
don't work. I don't know why.
Try this:
Set Ele = IE.document.getElementsByName("staffGroupCombo")
Ele(0).Click
If the page is not fully loaded like K.Davis write, you can insert a break after the IE says he is ready.
Do While IE.Busy = True Or IE.readyState <> 4: DoEvents: Loop
Application.Wait (Now() + TimeValue("00:00:05"))
Related
I'm new here and on VBA, it's my 2nd post and I don't speak english very well. So, please, take easy on me =D
Last week I was having some troubles trying to automatize some procedures on IE. My macro worked very well when opened on new windows, but when I tried to run the same macro on tabs it wasn't working. It seemed (maybe) the macro wasn't recognizing the actual tab. I post that problem here and a wonderfull guy called Deepak-MSFT helped me a lot. He taught me how to run the macro on tabs and it worked almost 100%.
Problems:
1 - The macro sometimes work, sometimes doesn't. Yesterday, for example, I was getting errors 424, 91 and, sometimes, it just opened another tab without insert the value (perheaps because of the "On Error Resume Next"). I think it was because one of the websites was slow. I tried to increase the TimeValue until 7 seconds but, even so, it didn't work. I tested during the whole day and it was extremely unstable, sometimes worked, and somtimes it doesn't. But today it's working (all the websites are stable). Any idea how to solve this instability?
2 - There are 2 websites (2nd and 3rd) where I use querySelector to find the box to insert the value. Both of them work on 70% of the PC's of my company and only those 2 websites doesn't work on the other 30%. I installed the same version of IE (11.0.9600), Excel (2007, SP3) and Windows (W7) on all of them, but even so, only those 2 websites with queryselector don't work. There are no errors. The macro just don't insert the value. Perhaps I'm missing something that make queryselector works on those PC's, but all the references match. I dig the first 5 pages on google trying to find a solution but I failed. I think there's a witch flying around those PC's. Could you help me?
3 - I have total instability trying to run my macros on Excel 2016 or other versions of Excel higher than 2007 at Windows 10. Does anyone have a good solution to adapt the program to run on Excel 2016 (all my company will run this version next year) without have to do all over again?
Thank you very much guys. Here is my code:
Sub ademo()
Dim i As Long
Dim URL As String
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
'TAB 1
URL = "https://servicos.ibama.gov.br/ctf/publico/areasembargadas/ConsultaPublicaAreasEmbargadas.php"
IE.Navigate2 URL
Do While IE.readyState = 4: DoEvents: Loop 'Do While
Do Until IE.readyState = 4: DoEvents: Loop 'Do Until
IE.document.getElementById("num_cpf_cnpj").Value = "demo1" 'Sheets("Main").Range("C10")
IE.document.getElementById("Emitir_Certificado").Click
'TAB 2 - DAP
On Error Resume Next
IE.Visible = True
IE.Navigate2 "http://smap14.mda.gov.br/extratodap/", 2048&
Application.Wait (Now + TimeValue("0:00:04"))
Set IE = GetIE("http://smap14.mda.gov.br/extratodap/")
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
Set doc = IE.document
On Error Resume Next
Set Target = IE.document.querySelector("#corpo > div > div > div:nth-child(1) > button")
Target.Click
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
doc.getElementById("txtCPF_CNPJ").Value = "demo2"
'TAB 3 - CNDT
IE.Visible = True
On Error Resume Next
IE.Navigate2 "http://aplicacao.jt.jus.br/cndtCertidao/inicio.faces", 2048&
Application.Wait (Now + TimeValue("0:00:04"))
Set IE = GetIE("http://aplicacao.jt.jus.br/cndtCertidao/inicio.faces")
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
Set doc = IE.document
On Error Resume Next
Set target2 = IE.document.querySelector("#corpo > div > div:nth-child(2) > input:nth-child(1)")
target2.Click
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
doc.getElementById("gerarCertidaoForm:cpfCnpj").Value = "demo3"
'TAB 4 - CND
On Error Resume Next
IE.Visible = True
IE.Navigate2 "http://servicos.receita.fazenda.gov.br/Servicos/certidao/CNDConjuntaInter/InformaNICertidao.asp?tipo=2", 2048&
Application.Wait (Now + TimeValue("0:00:04"))
Set IE = GetIE("http://servicos.receita.fazenda.gov.br/Servicos/certidao/CNDConjuntaInter/InformaNICertidao.asp?tipo=2")
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
Set doc = IE.document
On Error Resume Next
IE.document.getElementsByName("NI")(0).Value = "demo4"
'TAB 5 - IMPROBIDADE
IE.Visible = True
IE.Navigate2 "http://www.cnj.jus.br/improbidade_adm/consultar_requerido.php?validar=form", 2048&
Application.Wait (Now + TimeValue("0:00:04"))
Set IE = GetIE("http://www.cnj.jus.br/improbidade_adm/consultar_requerido.php?validar=form")
IE.document.getElementById("num_cpf_cnpj").Value = "demo5"
End Sub
Function GetIE(sLocation As String) As Object
Dim objShell As Object, objShellWindows As Object, o As Object
Dim sURL As String
Dim retVal As Object
Set retVal = Nothing
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
For Each o In objShellWindows
sURL = ""
On Error Resume Next 'because may not have a "document" property
'Check the URL and if it's the one you want then
' assign the window object to the return value and exit the loop
sURL = o.document.Location
On Error GoTo 0
If sURL Like sLocation & "*" Then
Set retVal = o
Exit For
End If
Next o
Set GetIE = retVal
End Function
I have a macro that connects to a web-page, gets some info and displays it on a user form (for further actions):
Private Sub UserForm_Initialize()
Dim login As String, password As String
Dim waittime As String
Dim arrForms As Variant
Dim ie As InternetExplorer
LoadingForm.Show vbModeless
LoadingForm.lblLoading.Caption = "Loading..."
waittime = "0:00:02"
login = "lgn"
password = "passwrd"
txtEndDate.Value = Format(Now(), "dd.mm.yyyy")
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
'open login page
ie.navigate "my link (internal company database)"
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
Application.Wait (Now + TimeValue(waittime))
'if already logged in, skip
On Error GoTo Skip_login
ie.document.getElementById("_58_login").Value = login
ie.document.getElementById("_58_password").Value = password
ie.document.getElementsByClassName("btn btn-primary")(0).Click
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
Application.Wait (Now + TimeValue(waittime))
Skip_login:
ie.navigate "my link (internal company database)"
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
Application.Wait (Now + TimeValue(waittime))
arrForms = GetListOfForms(ie) 'this is a function that reads the page,
'finds a table and converts its values to an array
'I tried to comment this line (maybe a bug in my function)
'but even without it the code does not work
For i = LBound(arrForms) To UBound(arrForms)
FormsList.AddItem (arrForms(i))
Next i
'Log out and quit IE
ie.navigate "my link (internal company database)"
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
Application.Wait (Now + TimeValue(waittime))
ie.document.getElementById("sign-out").Click
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
Application.Wait (Now + TimeValue(waittime))
ie.Quit
LoadingForm.Hide
End Sub
It worked fine for a few days. It also worked today. But it stopped working for an unknown reason (it just says"automation error" without reference to an error in my code). I was using it, closed the user form, then clicked to start macro again and it does not work. I tried to open older backups - they stopped working too. I did not change anything (links, login/password, any other line of code).
My user form does not have any uncommon user controls. It has the following controls only: text fields, lables, frames, listbox, and buttons)
I want to create a code in Excel Vba to help me click a js image button in a website.
Here is what i have tried.
Sub test()
Dim ie As Object
Set ie = New InternetExplorer
WebPage = "http://myweb.com" 'a makeup link, not really my site
ie.Visible = True
ie.Navigate WebPage
Application.Wait (Now() + TimeValue("00:00:05"))
ie.Document.getElementById("ctl00_ContentPlaceHolder1_tcSearchRoute_tabSearchRoute2_ibtnSearchR2").Click
End Sub
When I run the code, it says
RunTime Error '-2147217848(80010108)'
Automation error
The object invoked has disconnected from its clients.
Here is the html code for that js image button
<input type="image" name="ctl00$ContentPlaceHolder1$tcSearchRoute$tabSearchRoute2$ibtnSearchR2" id="ctl00_ContentPlaceHolder1_tcSearchRoute_tabSearchRoute2_ibtnSearchR2" src="../Images/button/btn_searchAccount.png" alt="Search Account" style="border-width:0px;">
Your .Click line seems ok to me. Have you been using ie.Quit, before the End Sub, to close off instances each time you run your code? Check how many InternetExplorer instances you have running for starters.
Use a proper page load wait of:
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
Then you could also try
ie.Navigate2 "http://myweb.com" & ie.Document.querySelector("#ctl00_ContentPlaceHolder1_tcSearchRoute_tabSearchRoute2_ibtnSearchR2").src
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
Or just retry you existing line.
You can try to create and set IE object like below.
Set ie = CreateObject("InternetExplorer.Application")
or try
Dim ie As SHDocVw.InternetExplorer
Set ie = New InternetExplorerMedium
or try
Set ie = GetObject("new:{D5E8041D-920F-45e9-B8FB-B1DEB82C6E5E}")
You can try adding one of these wait loops after you set your IE object or anytime the IE page changes/refreshes.
Set ie = CreateObject("InternetExplorer.Application")
Do While ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
While ie.busy
DoEvents
Wend
Do While IE.ReadyState = 4: DoEvents: Loop
Do Until IE.ReadyState = 4: DoEvents: Loop
Further, you can try to disable the enable enhanced protected mode option in IE settings.
Go to Tools-> IE options -> Advanced tab -> Security section - disable
"enable enhanced protected mode".
Reference:
VBA Error: The object invoked has disconnected from its clients
This will be a little vague as i cannot provide all the relevant information needed, but maybe someone is up for the challenge.
I am trying to download an excel file from a website and then save that excel file. Here is my code.
Dim ie As InternetExplorer
Set ie = New InternetExplorer
ie.Visible = True
ie.navigate "####"
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop
ie.document.getElementById("###").Click
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop
Application.SendKeys "%{o}"
Set ie = Nothing
ActiveWorkbook.SaveAs "####"
End Sub
The code works when I don't include anything after the sendkeys. If I include any code after the sendkeys the download will wait to download until after that code has been run. I tried using
Application.Wait Not + TimeValue("xx:xx:xx")
but that only served to pause the download as well. Is there any kind of loop that I can run similar to ie readystate loop listed below?
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop
Or another trick to finish the download before continuing the rest of my macro?
So I have some code to go to a website and then login. Then I need it to go to the password change URL. Sometimes when I run the code, I get the following error:
Runtime Error 424: Object Required
Sometimes the debugger says it is the first getelementbyid statement, but most times it says the issue is the last three getelementbyid statements. The code is below:
Dim ie As Variant
Dim strURL As String
Sub login()
Set ie = New SHDocVw.InternetExplorer
ie.Visible = True
ie.navigate "https://minecraft.net/profile"
While ie.Busy
DoEvents
Wend
ie.document.getElementById("username").Value = "ddd"
ie.document.getElementById("password").Value = "ddddddddddd"
Dim htmlForm As HTMLFormElement
Set htmlForm = ie.document.getElementById("loginForm")
htmlForm.submit
' **********************************************************************
'IE.Document.getElementById("username").Value = "ddddd"
' IE.Document.getElementById("password").Value = "ddddd"
' IE.Document.getElementById("signin").Click
'**********************************************************************
'Pause while page loads
Application.Wait (Now + #12:00:03 AM#)
ie.navigate "https://minecraft.net/profile/password"
ie.document.getElementById("oldPassword").Value = "oldpass"
ie.document.getElementById("password").Value = "enwapss"
ie.document.getElementById("passwordConfirmation").Value = "enwapss"
Set htmlForm = ie.document.getElementById("loginForm")
htmlForm.submit
End Sub
Thanks in advance!
It may be that the website isn't in a ready state, as in the site hasn't fully loaded when it's attempting to input the values.
After
ie.navigate "https://minecraft.net/profile/password"
Try adding
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
This will loop until the webpage has loaded similar, to the way you've done it in your above code with
Application.Wait (Now + #12:00:03 AM#)