VBA code doesn't work consistantly - excel

I'm new to using VBA. I'm trying to wrap my head around using it correctly. I have this code and it seems to work perfectly the 1st time around but then I can't get it to work again. I'm trying to get to the match summary page for basketball games played. If I could get some assistance it would be much appreciated
Sub Test()
Dim URL As String
Dim IE As InternetExplorer
Dim HTMLdoc As HTMLDocument
Dim TDelements As IHTMLElementCollection
Dim TDelement As HTMLTableCell
Dim i As Integer
URL = "http://www.flashscore.com/basketball/"
Set IE = New InternetExplorer
With IE
.Navigate URL
.Visible = True
While .Busy Or .ReadyState <> READYSTATE_COMPLETE: DoEvents: Wend
Set HTMLdoc = .Document
End With
Set TDelements = HTMLdoc.getElementsByTagName("td")
For Each TDelement In TDelements
If TDelement.Title = "Click for match detail!" Then
TDelement.Click
End If
Next
End Sub

try using this
Dim IE as Object
Set IE = CreateObject("InternetExplorer.Application")
--corrected

Your code actually looks fine with one small tweak- make sure to add:
IE.Quit
Set IE = Nothing
End Sub
Otherwise multiple IE instances would be hiding in the background- others have suggested using CreateObject("InternetExplorer.Application") but I much prefer using the methodology you used so you have a true InternetExplorer object that you can see its methods & properties if necessary..
I ran it and didn't get an errors, but also didn't get any TDs to meet the If clause- this could just be due to the timing of the website and its data, element.title is not an attribute I have seen used very often so perhaps this is the source of your issues and you should revisit what attribute you are checking to meet your if clause.
Hope this helps,
ThesilkCode

Related

VBA Excel click on href and fill in form

im trying to get some data from a website by using vba.
The data i want is from this site: https://www.uitvoeringarbeidsvoorwaardenwetgeving.nl/mozard/!suite16.scherm1168?mSel=145576
What i want the code to do is click on the purple bar with the pencil
on it so the screen appears for filters and than fill in a specific time frame in the filters.
When this is done i want to get the data that appears.
Im able to navigate to the site and click on the purple bar so the filter screen appears. but i cant fill in the dates
this is the code i have so far:
Dim IE As New SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLAs As MSHTML.IHTMLElementCollection
Dim HTMLA As MSHTML.IHTMLElement
Dim pastDate As MSHTML.IHTMLElement
Dim futuredate As MSHTML.IHTMLElement
IE.Visible = True
IE.Navigate "https://www.uitvoeringarbeidsvoorwaardenwetgeving.nl/mozard/!suite16.scherm1168?mGmr=66"
Do While IE.ReadyState <> READYSTATE_COMPLETE
Loop
Set HTMLDoc = IE.Document
Set HTMLAs = HTMLDoc.getElementsByTagName("a")
For Each HTMLA In HTMLAs
'Debug.Print HTMLA.className, HTMLA.getAttribute("href"), HTMLA.getAttribute("rel"), HTMLA.innerText
If HTMLA.getAttribute("href") = "https://www.uitvoeringarbeidsvoorwaardenwetgeving.nl/mozard/!suite16.scherm1168?mGmr=66#editmodal" Then
HTMLA.Click
Exit For
End If
Next HTMLA
Do While IE.ReadyState <> 4 Or IE.Busy:
DoEvents: Loop
Set HTMLInput = HTMLDoc.getElementById("frm_FKMT_B931_542_823883_dva_id1")
HTMLInput.Value = "01-01-2020" 'THIS GIVES AN ERROR?
The last line of code gives an error and i dont understand why??
This is the HTML code from the website that i want to change the value of:
<input name="FKMT_B931_542_823883_dva" class="datumveld form-control" id="frm_FKMT_B931_542_823883_dva_id1" type="text" pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}">
Thanks and sorry for the inconvience or poorly asked question, if there is anything else you guys need to now please feel free to ask!
Thank you!!
This is an example to fill the first date field. The IDs seems not very stable.
Beware: There is a pattern for the entered dates
pattern="(0[1-9]|1[0-9]|2[0-9]|3[01]).(0[1-9]|1[012]).[0-9]{4}"
There are some html events. I don't know if it is necessary to trigger them to make the dialog realy work.
Have you checked if the page works in IE?
Sub OpenAndFillForm()
Dim browser As Object
Dim url As String
Dim nodeToClick As Object
Dim nodeForm As Object
Dim nodeFirstDate As Object
url = "https://www.uitvoeringarbeidsvoorwaardenwetgeving.nl/mozard/!suite16.scherm1168?mGmr=66"
Set browser = CreateObject("internetexplorer.application")
browser.Visible = True
browser.navigate url
Do Until browser.readyState = 4: DoEvents: Loop
Set nodeToClick = browser.document.getElementByID("tabel2").getElementsByTagName("a")(0)
nodeToClick.Click
Application.Wait Now + TimeValue("00:00:02")
Set nodeForm = browser.document.getElementByID("tabel12")
Set nodeFirstDate = nodeForm.getElementsByClassName("datumveld")(0)
nodeFirstDate.Value = "31-12-2019"
End Sub

What is the correct element ID for this vba code?

I got the below vba code from this site. The code will automatically open the site in IE(will be using different url) and will import files as well. When I ran this code,it did not work due to incorrect elementsTagName and maybe InputType as well. What should be the correct codes? I am not sure. The second part is the html codes.
Please help check the codes.
Sub File_Test()
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim HTMLButton As MSHTML.IHTMLElement
Dim btnInput As MSHTML.IHTMLInputElement
Dim ie As Object
Dim pointer As Integer
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
ie.navigate "http://www.htmlquick.com/reference/tags/input-file.html"
Do While ie.readyState <> READYSTATE_COMPLETE
Loop
Set HTMLDoc = ie.document
Set HTMLButtons = HTMLDoc.getElementsByTagName("Upload Files")
For Each HTMLButton In HTMLButtons
For Each btnInput In HTMLButtons
If btnInput.Type = "button" Then
HTMLButton.Click btnInput.Value = "C:\temp\test.txt"
pointer = 1
Exit For
End If
Next
btnInput
If pointer = 1 Then Exit For
Next
End sub
<button title="Upload Files" class="button button--white xc-action-nav__button ng-binding ng-scope" type="button" loading-key="0" ng-click="setLoading('group1', '0'); " ng-disabled="isLoading('group1', null)"><span class="spinner-transition" ng-class="{'spinner spinner--is-loading': isLoading('group1', '0')}"></span> Upload Files</button>
Some pointers:
This HTMLButton.Click btnInput.Value = "C:\temp\test.txt" should be on two separate lines.
HTMLButton.Click
btnInput.Value = "C:\temp\test.txt"
I think the second line is redundant. Your code is missing the more complex instructions required to interact with the file dialog for inputing the filepath. A subject for a whole other question which has been addressed elsewhere on SO.
The "buttons" are input tag elements and you need to limit to the appropriate three.
Dim uploads As Object, i As Long
Set uploads = ie.document.querySelectorAll("#examples [type=file]")
For i = 0 To uploads.Length-1
uploads.item(i).click
'other code
Next
My advice would be to try and code with the actual url and share the problems you are having with the actual scenario. The code above, IMO, is not fit for purpose for the url given.
I tested it but it is not working. I received Run Time Error '-2147417848 (80010108). THE OBJECT INVOKED HAS DISCONNECTED FROM ITS CLIENTS after I clicked F8 in the Loop line.. Below is the new code as per your suggestion. What is causing this issue? Apologies if I postes my comment here as a simple Add Comment does not allow me to put the codes. Thanks for your time!
Private Sub CommandButton21_Click() Dim ie As Object Dim uploads As Object, i As Long Set ie = CreateObject("internetexplorer.application") ie.Visible = True ie.navigate "http://www.htmlquick.com/reference/tags/input-file.html" Do While ie.readyState <> 4 Loop Set uploads = ie.document.querySelectorAll("#examples [type=file]") For i = 0 To uploads.Length - 1 uploads.Item(i).Click'other code Next End Sub
 

getElementById won't work in VBA, error 438

I am relatively new at VBA (I know the basics, but not much else) and I am trying to get some code set up that will fill out online forms for me, but when I run my code I get a 438 error:
object doesnt support this property or method
when it gets to
ie.document.getElementById ("q")
I have added the HTML object library and Microsoft internet controls to my references. I have looked at tons of online forums. I have even copied and pasted an entire script directly into VBA. Nothing will make it use getElementById(). Here is my code:
Sub internetstuff()
Dim ie As Object
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
ie.navigate ("https://www.google.com/")
Set searchbx = ie.document.getElementById("q")
searchbx.Value = "Howdy!"
End Sub
What should happen is that it should open InternetExplorer, go to Google, and populate the search bar with "Howdy!".
Instead, It only opens google, then I get the error message and it stops running.
Because "q" is not an ID, it's a Name.
You have to use GetElementsByName and select the 1st Element
try this:
Sub internetstuff()
Dim ie As Object
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
ie.Navigate ("https://www.google.com/")
Do Until ie.ReadyState >= 4
DoEvents
Loop
Set searchbx = ie.document.getElementsByName("q")(0)
searchbx.Value = "Howdy!"
End Sub
I have also added a waiting Event, in case it takes time to load Google.
Result:
A more concise and efficient way is to use querySelector to return first match for the name attribute
Option Explicit
Public Sub internetstuff()
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate2 "https://www.google.com/"
While .Busy Or .readyState < 4: DoEvents: Wend
.document.querySelector("[name=q]").Value = "Howdy"
Stop '<delete me later
.Quit
End With
End Sub

Excel VBA force shutdown IE

I am currently using the following sub to close my IE after automating:
Public Sub CloseIE()
Dim Shell As Object
Dim IE As Object
Set Shell = CreateObject("Shell.Application")
For Each IE In Shell.Windows
If TypeName(IE.Document) = "HTMLDocument" Then
IE.Quit
End If
Next
End Sub
This works great but the problem occurs when I try to run the IE code again, I get the following:
Run-time error '-2147023706 (800704a6)':
Automation error
A system shutdown has already been scheduled.
After 20 secs, I can re-run the code. Is there any way of "force closing" IE so that I can run the code again directly after without the error?
EDIT:
Heres the code that initiates IE:
Sub testSub()
Dim IE As Object, Doc As Object, strCode As String
Set IE = CreateObject("internetexplorer.application")
IE.Visible = True
IE.Navigate "website name"
Do While IE.ReadyState <> 4: DoEvents: Loop
Set Doc = CreateObject("htmlfile")
Set Doc = IE.Document
CODE HERE
CloseIE
End Sub
I used a simple procedure to create an InternetExplorer object, navigate, then close it using IE.Quit and Set IE = Nothing.
Apparently after closing, the internet was still running in the background for about another minute (I noticed it using task manager, background processes). I went into Internet Explorer options and unclicked “delete browsing history on exit”.
That fixed my issue. I am not sure why IE takes that long to clear the history and I’m not sure if there is a workaround but it is the only viable option for me thus far.
Modify your main sub to Quit the IE application, and then set the object variable to Nothing:
Sub testSub()
Dim IE As Object, Doc As Object, strCode As String
Set IE = CreateObject("internetexplorer.application")
IE.Visible = True
IE.Navigate "website name"
Do While IE.ReadyState <> 4: DoEvents: Loop
Set Doc = CreateObject("htmlfile")
Set Doc = IE.Document
'### CODE HERE
IE.Quit
Set IE = Nothing
End Sub
You will not need the CloseIE procedure anymore.

Copy from excel and paste into online form

Firstly may I apologise for the fact that I am not the best with computers,
I have quite a large excel sheet for which I have to copy and paste 10 columns per row into an online form.
Is it possible to create a macro for this and if yes how can I do so.
Also please keep in mind that I am at work, so I'm limited from the use of plugins and I unfortunately have to use internet explorer.
Your help would be much adored,
Thank You
Yes it is possible. You can use IE to automate this using vba.
Sub xtremeExcel()
Dim HTMLDoc As HTMLDocument
Dim oBrowser As InternetExplorer
sURL = "*******Paste URL Here************"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.navigate sURL
oBrowser.Visible = True
Do
Loop Until oBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = oBrowser.document
'Use firebug to identify the textbox or object you need. and you can set its value like
'HTMLDoc.GetElementByID("abcd").value="xyz"
End Sub

Resources