Copying Selected Information from Internet Explorer - vba

I've created a IE based VBA script in Excel using. The VBA script opens up IE, navigates to a web site, logs in to the site, enters in search criteria and opens a new window. I used the function GetIE to mirror that new windows website back to the original instance of IE so the VBA script can stay focused on the original instance. It then clicks a link on that window and then highlights some pricing information. But that's where I'm stuck. I desperately need code that will simply copy what i've highlighted to my clipboard. Here is the code posted:
Sub ExtractPMDPricing()
Dim core As ICore
Set core = New OpenTwebstLib.core
Dim IE As InternetExlorer
Set IE = CreateObject("Internet Explorer")
Dim browser As IBrowser
Set browser = core.StartBrowser("xxxxxxxxxxxxxxxx")
Range("A1").Select
Selection.Copy
Call browser.FindElement("div", "id=footer-position-placeholder").Click
Call browser.FindElement("a", "uiname=log in, index=1").Click
Call browser.FindElement("input text", "id=erznr").InputText(ActiveCell.Value)
Call browser.FindElement("td", "index=2").Click
Call browser.FindElement("input button", "id=sub").Click
Application.Wait (Now + #12:00:06 AM#)
Call GetIE
Call browser.FindElement("span", "id=selectionctrl_MATCONTSMALLCTRL_navigatorctrl_treeselectionctrl_MATCONTSMALLCTRL_navigatorctrl_Prices-cnt-start").Click
Call browser.FindElement("input text", "id=selectionctrl_MATCONTSMALLCTRL_subcatviewerctrl_selectionctrl_mod_ergebnis_ga[1].kbetr").RightClick
txt = IE.document.parentWindow.clipboardData.GetData("TEXT")
Range("B2").Select
ActiveCell.PasteSpecial
End Sub
' ZVI:2011-05-30 VBA Macro For Already Open IE Window
' Reference required: Tools - References - Microsoft Internet Controls
Function GetIE()
Dim shellWins As ShellWindows
Dim IE As InternetExplorer
Set shellWins = New ShellWindows
If shellWins.Count > 0 Then
' Get IE
Set IE = shellWins.Item(0)
Else
' Create IE
Set IE = New InternetExplorer
IE.Visible = False
End If
IE.Navigate "xxxxxxxxxxxxxxxx"
Set IE = Nothing
Set shellWins = Nothing
End Function
The copy code I need should fit in right below the last Call browser.findelement line before the end of the sub above Range ("B2").

txt=ie.document.parentwindow.clipboardData.GetData("TEXT")
this gets clipboard. Use Setdata.
Also you can give browser commands.
Executes a command on an OLE object and returns the status of the command execution using the IOleCommandTarget interface. (ie in basic ie.execwb 5, 0)
Syntax
object.ExecWB( _
cmdID As OLECMDID, _
cmdexecopt As OLECMDEXECOPT, _
[pvaIn As Variant,] _
[pvaOut As Variant])
Parameters
cmdID
Long that represents the identifier of the command to execute. For more information on command identifiers, see MSHTML Command Identifiers.
cmdexecopt
OLECMDEXECOPT value that specifies the command options.
pvaIn
Optional. A Variant used for specifying command input arguments.
pvaOut
Optional. A Variant used for specifying command output arguments.
IDM_COPY Command ID
--------------------------------------------------------------------------------
Copies the current selection to the clipboard.
C++ Information
Command group CGID_MSHTML (defined in mshtmhst.h)
Symbolic constant IDM_COPY
User interface None. Set nCmdExecOpt to OLECMDEXECOPT_DONTPROMPTUSER.
IOleCommandTarget::Exec parameters pvaIn Set to NULL.
pvaOut Set to NULL.
Header file mshtmcid.h
Applies to IHTMLDocument2::execCommand, IHTMLDocument2::queryCommandEnabled, IHTMLDocument2::queryCommandIndeterm, IHTMLDocument2::queryCommandState, IHTMLDocument2::queryCommandSupported, IHTMLDocument2::queryCommandValue, IOleCommandTarget::Exec, IOleCommandTarget::QueryStatus.
Minimum Availability
Internet Explorer 4.0 and later.

Related

Selenium VBA: Fill a Windows Popup to upload a file

I'm not able to have interaction with Windows PopUp to write a dedicated path to upload a file in VBA using Selenium due to Chrome browser.
I have found some solutions in Python but nothing in VBA. This is why I have tried to convert the code in VBA but without success.
Find below an example code:
Sub Fullfil_Windows_PopUp()
Dim driver
Dim elem
Set Waiter = CreateObject("Selenium.Waiter")
Set Assert = CreateObject("Selenium.Assert")
Set driver = CreateObject("Selenium.ChromeDriver")
'open the browser and the page
driver.Get "https://fr.imgbb.com/"
While Waiter.Not(InStr(driver.Title, "ImgBB — Upload Image — Hébergement d'images gratuit")): Wend
'open upload window
Set elem = driver.FindElementsByXPath("//*[#id='home-cover-content']/div[2]/a").Item(1)
elem.Click
'Trial 1
driver.SwitchToWindowByTitle "Ouvrir" '--> NOK (error window not found)
driver.SendKeys "D:\Test.jpg"
'Trial 2
driver.SwitchToAlert.SendKeys "D:\Test.jpg" '--> NOK (error No Alert present)
'Trial 3
Set wsh = CreateObject("WScript.Shell")
wsh.SendKeys "D:\Test.jpg" '--> NOK (no action)
End Sub
Thanks in advance for your suggestions
I have used a "back door" to fill the file name into the filemanager window.
As the cursor is already into the filename field of the window, I have created an external script in VBS to write the file name (and 2x TAB + ENTER to validate the window).
Below the code of the VBS file:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "D:\Test.jpg"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{ENTER}"
And I execute this script after to have open the filemanager window with selenium:
Sub Fullfil_Windows_PopUp()
Dim driver
Dim elem
' Chrome browser
Set driver = CreateObject("Selenium.ChromeDriver")
'open the browser and the page
driver.Get "https://fr.imgbb.com/"
Sleep 1000
' Open upload window
Set elem = driver.FindElementsByXPath("//*[#id='home-cover-content']/div[2]/a").Item(1)
elem.Click
' Write the filename with VBS script
Set oWsh = CreateObject("Shell.Application")
oWsh.ShellExecute "D:\filename.vbs"
Set oWsh = Nothing
Sleep 1500
End Sub
But I continue to search a solution directly with Selenium because for example, the filename is directly indicated into the VBS File and this is not easy to use it like a variant.
#Armin's answer works quite well if you are in a similar quandary. I don't know of any other method at present to interact with a file window at upload point.
For more details, a VBS file is a Microsoft VB-Script file. You can create this using Notepad, putting in the code, save as, change file name, include ".vbs" extension and change file type to all files.
If you use the code in the answer as it is, you're likely to be greeted with an unfriendly "Undefined Variable" error so you should declare the variable first as an object:
Dim oWsh as Object
Depending on your code, you may also be greeted with an error for the "Sleep*" command used. You can change this to using an implicit or explicit "Wait" as needed:
driver.Wait 1500
Cheers!

VBA with Excel and IE: Can't get the source right source code?

I'm currently trying to automate my IE at work with VBA and Excel, because we have some repetitive tasks to complete in an SAP System which is called within the Internet Explorer.
So far I am able to start IE and navigate to the starting page of our System.
I looked on the source code from the Sap System to search for an id from a div (lets say its 'SampleID'). But if I try to click it via VBA I only get returned 'nothing'. So I tried to print out the source code via VBA Debug.Print to look at the problem. And here's the thing:
The source code that gets printed is completely different from the Website's Source Code. In the printed code for example is a iframe that I can't find in the website source code. So that's the reason I can't find my div and any other objects, because they are not in the code that VBA is searching through.
Can anyone tell me what's going wrong? Why are the source codes completely different?
Sub stgGo(){
Dim i As Long
Dim IE As InternetExplorerMedium
Dim objElement As Object
Dim objCollection As Object
Set IE = New InternetExplorer
IE.Visible = True
IE.Navigate ("URL")
'waiting 10 seconds to be really sure javascript is ready
Application.Wait (Now + TimeValue("0:00:10"))
'printing out the false source code
Debug.Print strHTML = myIE.Document.body.innerHTML
Set objCollection = IE.document.getElementsByTagName("div")
i = 0
While i < objCollection.Length
If objCollection(i).ID = "SampleID" Then
objCollection(i).Click
End If
i = i + 1
Wend
End Sub

My excel macro generates errors inconsistently

I am working on a macro to automate some web browser stuff and there is an intermittent runtime error 91 "object variable or with block variable not set". I have been playing around with how I declare and create my browser object but nothing is working.
Sub Morning_Script()
Dim WebBrowser As Object
Set WebBrowser = New InternetExplorerMedium
WebBrowser.Visible = True
WebBrowser.navigate "www.google.com"
While WebBrowser.Busy = True
DoEvents
Wend
WebBrowser.document.getElementById("lst-ib").Value = "test"
'WebBrowser.document.getElementById("verify").Value = Worksheets("Sheet1").Range("B2")
'WebBrowser.document.getElementById("institution").Value = "xxx"
'Worksheets("Sheet1").Range("B1").Clear
'Worksheets("Sheet1").Range("B2").Clear
End Sub
The URL has been changed to a public website and the form entry has been commented out for now.
If you would prefer to avoid fixed timers, try this one:
Dim objElement As Object: Set objElement = Nothing
While objElement Is Nothing
Set objElement = WebBrowser.document.getElementById("lst-ib")
DoEvents
Wend
objElement.Value = "test"
If you would like to refer to verify and institution to, you would have to implement this scheme for them, too and wait until all three variables are non-nothing. You may also want to set a timeout or maximum retry number if there is a really great number of pages to download.

vba can not find opening IE 11 Browser.

I have a vba code which can upload the data from an excel sheet to a website. However, the code works fine in Win7 System and IE browser 8,but it does not work on a win8 IE browser 11.
Here are part of the code:
Dim objIE As SHDocVw.InternetExplorer
Dim htmlDoc As MSHTML.HTMLDocument
Dim htmlFrame As MSHTML.HTMLFrameElement
Dim frame As HTMLIFrame
Dim htmlElement As HTMLDTElement
Dim myDoc As Object
Set curSheet = ActiveWorkbook.ActiveSheet
Set oShApp = CreateObject("Shell.Application")
For Each oWin In oShApp.Windows
If oWin.Name = "Windows Internet Explorer" Then
Set IE = oWin
Exit For
End If
Next
If IE Is Nothing Then
MsgBox ("Please sign into Avocado, then re-run this macro")
Set IE = New InternetExplorerMedium
IE.Visible = True
IE.navigate "https://www.google.com"
Exit Sub
End If
Sheets("Prepare").Select
fPathName = Cells(5, 5)
Call MakeFolders(fPathName)
Call MakeFolders2(fPathName)
Call MakeFolders3(fPathName)
'fFileName = fPathName & "\*.xls"
fFileName = Dir(fPathName & "\*.xls")
The code runs in a loop when enters the statement : "If IE Is Nothing Then"
Even when the google site is opened, the program still keeps prompting out the msgBox, and reopen the website again and again, and it never executes to the last part "Sheets("Prepare").Select". I am very confused because it works perfect in the IE 8 browsers. I am wondering if there is any difference between IE11 and IE8 in terms of vba IE function.
Please take a look up it and give me some ideas on this, your help is greatly appreciated. Thank you very much.
I ran into the identical problem and found, that the window name of the shell.application has changed in IE 11. Earlier versions had the name "Windows Internet Explorer", but IE 11 uses only "Internet Explorer"
If you change your if condition accordingly, it will work again ...
I think you are using an old version of internet explorer. Use the code I provided bellow and see if it works. Please make sure you have the following references added to your project:
Microsoft HTML Object Library
Microsoft Internet Controls.
If you are not sure how to add the references to your code check out this link.External References
Sub Test()
Dim objIE As InternetExplorer
Dim htmlDoc As HTMLDocument
Dim htmlFrame As HTMLFrameElement
Dim frame As HTMLIFrame
Dim htmlElement As HTMLDTElement
Dim myDoc As Object
Dim curSheet As Worksheet
' Set the variables
Set curSheet = ActiveWorkbook.ActiveSheet
Set objIE = New InternetExplorer
' Make the browser visible and navigate
With objIE
.Visible = True
.navigate "https://www.google.com"
End With
WaitForInternetToLoad objIE
Sheets("Prepare").Select
fPathName = Cells(5, 5).Value
Call MakeFolders(fPathName)
Call MakeFolders2(fPathName)
Call MakeFolders3(fPathName)
'fFileName = fPathName & "\*.xls"
fFileName = Dir(fPathName & "\*.xls")
End Sub
Sub WaitForInternetToLoad(ByRef ie As InternetExplorer)
Do
dovents
Loop While Not ie.readyState = READYSTATE_COMPLETE
End Sub
Extra Information.
Hi I see you are having some trouble with this and I want to extend my help.
Let's start by the fact that you are using two external libraries in your code; and you should have references set to them for the code to work properly. See my picture I have highlighted the libraries yellow.
What are the differences:
Microsoft Internet Controls
Is the one that takes care of the internet object. It creates an internet explorer application and it navigates to certain links. Once it finishes navigating to the url then " internet object" has a "document". This object cannot do anything else.
Microsoft HTML Object Library
This library takes care of the Html document. And as you probably guessed you will assign the "document" from the previous object (internet explorer) to a HTML document variable and then you can do further manipulation.

Reading Web Pages using Excel VBA

I want to read web pages using Excel VBA. How do I carry out this task? Is it even possible?
Coming from Excel 2003, yes this is possible - you may use the SHDocVw.InternetExplorer and MSHTML.HTMLDocument objects to call a web page, gain control over and interact with the DOM object. After creating references to Microsoft HTML Object Library (...\system32\MSHTML.TLB) and Microsoft Internet Control (...\system32\ieframe.dll) you can play with the following example:
Sub Test()
Dim Browser As SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
Set Browser = New SHDocVw.InternetExplorer ' create a browser
Browser.Visible = True ' make it visible
Application.StatusBar = ".... opening page"
Browser.navigate "http://www.google.com" ' navigate to page
WaitForBrowser Browser, 10 ' wait for completion or timeout
Application.StatusBar = "gaining control over DOM object"
Set HTMLDoc = Browser.document ' load the DOM object
WaitForBrowser Browser, 10
' at this point you can start working with the DOM object. Usefull functions are
' With HTMLDoc
' .getElementByID(string)
' .getElementsByTagName(string)
' .getElementsByName(string)
' .getAttribute(string)
' .setAttribute string, string .... to change field values, click a button etc.
' End With
Application.StatusBar = "" ' time to clean up
Browser.Quit
Set HTMLDoc = Nothing
Set Browser = Nothing
End Sub
Sub WaitForBrowser(Browser As SHDocVw.InternetExplorer, Optional TimeOut As Single = 10)
Dim MyTime As Single
MyTime = Timer
Do While Browser.Busy Or (Timer <= MyTime + TimeOut)
DoEvents
Loop
' if browser still busy after timeout, give up
If Browser.Busy Then
MsgBox "I waited for " & Timer - MyTime & " seconds, but browser still busy" & vbCrLf & _
"I give up now!"
End
End If
End Sub
You can use VBA to automate IE (plenty of examples via Google) or you can fetch the page directly using an instance of MSHTTP (ditto plenty of examples on the web). Which is best for your needs will depend on exactly what you want to do. Hard to say more without more detailed requirements.