Control Internet Explorer from VBA - vba

I have created a macro/userform that creates an html file and want Internet Explorer 11 to show the page.
When you use the userform you create new data that should be shown on the page. How do I refresh the page on IE11?
I tried using meta refresh, but if the userform writes the page at the moment IE refreshes the page goes blank and stops from refreshing.
Another method I tried is sendkeys but it doesn't seem to work.
AppActivate "The page - Internet Explorer"
SendKeys "{F5}", True
nothing happens.
Are there any other options to make sure the page is refreshed and always visible? (meaning don't refresh when the file is in use by the userform)

If page is already opened then you need to find that specific page and then you can try to refresh it. you can try to find the page by its title.
See the example code below.
Sub demo1()
flag = 0
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
On Error Resume Next
my_url = objShell.Windows(x).Document.Location
my_title = objShell.Windows(x).Document.Title
If my_title Like "Microsoft" & "*" Then
Set ie = objShell.Windows(x)
ie.Refresh
flag = 1
Exit For
Else
End If
Next
If flag = 0 Then
Debug.Print ("A matching webpage was NOT found")
Else
Debug.Print ("A matching webpage was found")
End If
End Sub
Try to modify the title in code to match with your web page.

Related

VBA Internet Explorer Automation issue

I try to make a VBA macro that will
Activate an open internet page
Enter text in a field
Click on a button
click on a link in the result
My code is the following for part 1 and it works
AppTitle = "Search Outbound Batches"
AppActivate AppTitle
Set oApp = CreateObject("Shell.Application")
For i = 0 To 25
strName = ""
On Error Resume Next
strName = oApp.Windows(i).document.Url
If InStr(strName, "http://...") Then
Set oIE = oApp.Windows(i)
Exit For
End If
Next
For part 2 I try this but it's nor working : nothing is entered
Set imputtext = oIE.document.getElementsByName("SBatchNumber")
inputtext.Value = "3424"
Result of the inspection Element on the webpage:
For part 3 I tried this but not working neither
Set tags = ie.document.getElementsByTagName("button")
For Each tagx In tags
If tagx.innerText = "Go" Then
tagx.Click
Exit For
End If
Next
This is the inspection detail:
For part 4 this but not working neither
Set Batch = oIE.document.All("N3:BatchNumber:0")
Batch.Click
I send you also a printscreen of the web page in order you have a better understanding:
Could you please help me to solve all these issues ?
Thanks a lot,
Oliver

Can't click on some dots to scrape information

I've written a script in vba in combination with IE to click on some dots available on a map in a web page. When a dot is clicked, a small box containing relevant information pops up.
Link to that website
I would like to parse the content of each box. The content of that box can be found using class name contentPane. However, the main concern here is to generate each box by clicking on those dots. When a box shows up, it looks how you can see in the below image.
This is the script I've tried so far:
Sub HitDotOnAMap()
Const Url As String = "https://www.arcgis.com/apps/Embed/index.html?webmap=4712740e6d6747d18cffc6a5fa5988f8&extent=-141.1354,10.7295,-49.7292,57.6712&zoom=true&scale=true&search=true&searchextent=true&details=true&legend=true&active_panel=details&basemap_gallery=true&disable_scroll=true&theme=light"
Dim IE As New InternetExplorer, HTML As HTMLDocument
Dim post As Object, I&
With IE
.Visible = True
.navigate Url
While .Busy = True Or .readyState < 4: DoEvents: Wend
Set HTML = .document
End With
Application.Wait Now + TimeValue("00:0:07") ''the following line zooms in the slider
HTML.querySelector("#mapDiv_zoom_slider .esriSimpleSliderIncrementButton").Click
Application.Wait Now + TimeValue("00:0:04")
With HTML.querySelectorAll("[id^='NWQMC_VM_directory_'] circle")
For I = 0 To .Length - 1
.item(I).Focus
.item(I).Click
Application.Wait Now + TimeValue("00:0:03")
Set post = HTML.querySelector(".contentPane")
Debug.Print post.innerText
HTML.querySelector("[class$='close']").Click
Next I
End With
End Sub
when I execute the above script, it looks like it is running smoothly but nothing happens (I meant, no clicking) and it doesn't throw any error either. Finally it quits the browser gracefully.
This is how a box with information looks like when a dot gets clicked.
Although I've used hardcoded delay within my script, they can be fixed later as soon as the macro starts working.
Question: How can I click each of the dots on that map and collect the relevant information from the popped-up box? I only expect to have any solution using Internet Explorer
The data are not the main concern here. I would like to know how IE work in such cases so that I can deal with them in future cases. Any solution other than IE is not I'm looking for.
No need to click on each dots. Json file has all the details and you can extract as per your requirement.
Installation of JsonConverter
Download the latest release
Import JsonConverter.bas into your project (Open VBA Editor, Alt + F11; File > Import File)
Add Dictionary reference/class
For Windows-only, include a reference to "Microsoft Scripting Runtime"
For Windows and Mac, include VBA-Dictionary
References to be added
Download the sample file here.
Code:
Sub HitDotOnAMap()
Const Url As String = "https://www.arcgis.com/sharing/rest/content/items/4712740e6d6747d18cffc6a5fa5988f8/data?f=json"
Dim IE As New InternetExplorer, HTML As HTMLDocument
Dim post As Object, I&
Dim data As String, colObj As Object
With IE
.Visible = True
.navigate Url
While .Busy = True Or .readyState < 4: DoEvents: Wend
data = .document.body.innerHTML
data = Replace(Replace(data, "<pre>", ""), "</pre>", "")
End With
Dim JSON As Object
Set JSON = JsonConverter.ParseJson(data)
Set colObj = JSON("operationalLayers")(1)("featureCollection")("layers")(1)("featureSet")
For Each Item In colObj("features")
For j = 1 To Item("attributes").Count - 1
Debug.Print Item("attributes").Keys()(j), Item("attributes").Items()(j)
Next
Next
End Sub
Output

VBA IE automation: loop for opening multiple tabs with identical names and URLs and performing same action in them

Suppose I have a list of identical URLs in spreadsheet column.
I navigate to the URL manually, then I want my macro to open every URL in separate IE tab and also click a specific button in it.
I use custom function FindIEObject to grab browser window by name or URL.The problem is that obviously each tab will have the same name and URL, so I need to find another way to differentiate between them and set each one as current IE object. My first thought was to assign a dummy name or a number to each tab as it gets created. I suppose this part should go somewhere after IE.Navigate Cell.Value in the loop.
Here is my code, currently opening all the tabs, but clicking the element only in the first one:
Private page_title As String
Public IE As InternetExplorerMedium
Sub intercept()
FindIEObject ("Allegro")
For Each Cell In Columns("A").Cells.SpecialCells(xlConstants)
IE.Navigate Cell.Value, CLng(2049) ' open URL in new tab
'Call MyWait
For Each element In IE.Document.GetElementsByTagName("img")
If element.GetAttribute("src") = "https://assets.allegrostatic.com/opbox/allegro.pl/homepage/Main%20page%20-%20new_SG_categories%20-%20icons/c4c8134ad8ae75c9d1070e7bee8cbeea.svg" Then
element.Click
Exit For
End If
Next element
Next Cell
End Sub
Sub MyWait()
Do While IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
End Sub
Public Function FindIEObject(target As String) As InternetExplorerMedium
marker = 0
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
On Error Resume Next ' sometimes more web pages are counted than are open
page_url = objShell.Windows(x).Document.Location
page_title = objShell.Windows(x).Document.Title
If page_title Like target & "*" Then 'compare to find if the desired web page is already open
Set IE = objShell.Windows(x)
marker = 1
Exit For
End If
Next
If marker = 0 Then
MsgBox ("A matching webpage was NOT found")
Else
MsgBox ("A matching webpage was found")
End If
End Function
I would be grateful for any suggestions.

VBA: New (or Redefined?) Internet Explorer Object In Same Window

I'm creating a macro that will navigate to a login page, log in, navigate to another page and scrape data, and then loop through 100-200 more pages scraping data from each.
So far I've gotten it to the point of logging in, navigating to the second page, and scraping the first bit of data. But so far the only way I can get it to work is if the second page opens in a new window. Since I ultimately have to go through 100-200 pages, I'd rather not use a new window for each one.
For this example let's just say that the only data I'm trying to scrape is the page title.
Option Explicit
Sub admin_scraper()
Dim ie As Object
Dim doc As Object
' Get through log in page
Set ie = CreateObject("internetexplorer.application")
With ie
.navigate "http://example.com/login" 'Page title is "Page 1"
.Visible = True
End With
While ie.Busy Or ie.readyState <> 4
DoEvents
Wend
ie.document.forms(0).all("Username").Value = "user"
ie.document.forms(0).all("Password").Value = "abc123"
ie.document.forms(0).submit
'Navigate to second page and pull page title
Set ie = CreateObject("internetexplorer.application") '***Line in question
With ie
.navigate "http://example.com/Products" 'Page title is "Page 2"
.Visible = True
End With
While ie.Busy Or ie.readyState <> 4
DoEvents
Wend
Set doc = ie.document
Debug.Print doc.Title
End Sub
*** If I include this line the code works as expected (console prints "Page 2"), but it opens the second page in a new window. If I don't include this line, the second page opens smoothly in the same window, but the console prints "Page 1."
Any way I can get it to open each new page in the same window while making sure it pulls data from the new page? Or if it has to be in a new window, any way to automatically close the old window each time?

VBA Automation - Downloading a file using IE 11 (64bit)

This question seems to have been asked dosens of times, however none of the solutions I have found seem to be able to solve my problem.
As the webpage is using a certificate token I am forced to log on to the webpage manually before I can activate the VBA script, which is no problem. An important note is that the link to the report is dynamic and therefore I cannot link directly to the report itself and therefore I have to navigate the webpage with my Script. Below you find the script i am using to locate the window I have logged on to the webpage with:
Sub WebPageOpen()
Dim HTMLDoc As HTMLDocument
Dim oHTML_Element As IHTMLElement
On Error GoTo Err_Clear
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For X = 0 To (IE_count - 1)
On Error Resume Next ' sometimes more web pages are counted than are open
my_url = objShell.Windows(X).document.Location
my_title = objShell.Windows(X).document.Title
If my_title Like "MY Webpage name" Then 'compare to find if the desired web page is already open
Set IE = objShell.Windows(X)
marker = 1
Exit For
Else
End If
Next
If marker = 0 Then
MsgBox ("Webpage is not open - Please log on to webpage")
Exit Sub
Else
End If
Do
' Wait till the Browser is loaded
Loop Until IE.readyState = READYSTATE_COMPLETE
' I have removed all my navigation commands here,as it would just be bloating the query. It clicks the link and the Save/open ribbon appears in IE.
End sub
Can anyone help me with some sort of solution to how I can interact with the Open/Save as ribbon which appears when I download the file?
That ribbon is called Notification bar.
You can use Alt+N to focus on the Notification Bar. And then send {tab} key to navigate to the specific button.
With VBA, you may use Autohotkey.dll or AutoItX3.dll to send these hotkey combinations.
Add reference to AutoItX3.dll (for both 32-bit and 64-bit OS)
Append the following
set X=CreateObject("AutoItX3.Control")
X.send !N{tab}{down 2}{enter} 'This is for Save-as