Download google script results to Excel VBA - vba

I have a webApp (google sheets) that should transfer data to an Excel file.
In the script i'm currently returning something with ContentService.createTextOutput(), see this link
In the VBA i tried with different codes, for example with
Sub Test()
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", "https://script.google.com/macros/s/AKfycbxU2ZL39IdtMzQXu0OLJZz3shSOx1JNTCbe1_SCxunIimLJVqY/exec", False
WinHttpReq.Send
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile "c:\test.txt", 2
oStream.Close
End If
End Sub
With Runtime error 70, I tried also with WinHttp.WinHttpRequest.5.1 but with other errors (I suppose timeout)
I can download the whole file with this link without problems, I see that the ContentService redirect the browser page (and the direct download does not) but I really don't know how to handle it with VBA (and I didn't find anything useful googleing)
Thanks for help

I found right now a solution with InternetExplorer.Application that is working, after hours of attempts and 10 minutes after making the question
Sub Test2()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim IE As Object
'Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = False
'Define URL
URL = "https://script.google.com/macros/s/AKfycbxU2ZL39IdtMzQXu0OLJZz3shSOx1JNTCbe1_SCxunIimLJVqY/exec"
'Navigate to URL
IE.Navigate URL
' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.ReadyState = 4: DoEvents: Loop 'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
MsgBox (IE.document.body.innerText)
'Unload IE
Set IE = Nothing
End Sub

Related

vba code for sending texts from excel to whatsapp

I have previously used selenium webdriver for sending messages to whatsapp via VBA. But now, I need some pure vba codes to send text from excel sheet. What I discovered InternetExplorer does not support whatsapweb. I searched the internet I discovered some tutorial where it uses APPACTIVATE method for using CHROME.
AppActivate "Chrome"
But I was not able to use chrome with this code. Can anyone help with code below/ suggesting links will also be benefital for sending messages through vba to whatsapp without third party applications.
Sub Automate_IE_Load_Page()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
'Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True
'Define URL
URL = "https://web.whatsapp.com/"
'Navigate to URL
IE.navigate URL
' Statusbar let's user know website is loading
Application.StatusBar = URL & " is loading. Please wait..."
' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.readyState = 4: DoEvents: Loop 'Do While
Do Until IE.readyState = 4: DoEvents: Loop 'Do Until
'Webpage Loaded
Application.StatusBar = URL & " Loaded"
'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
End Sub
On internet I saw excel formula where it hyperlinks the text message to whatsapp from formula bar, but HYPERLINK formula opens the edge browser not IE. Could not I use also Edge browser in vba library instead IE.Application?
=IF(G3="","",HYPERLINK("https://web.whatsapp.com/send?phone=%2B"&VLOOKUP(B3,'Employee Master'!A:D,4,0)&"&text=" & H3&"&app_absent=1&send=1",")"))

The remote server machine does not exist or is unavailable for specific website

I tried to open website using below VBA code:
Dim IE As Object
Dim doc As Object
Dim strURL As String
Set IE = CreateObject("InternetExplorer.Application")
With IE '
.Visible = True
.navigate "https://Google.com"
Do Until .readyState = 4
DoEvents
Loop
It's working for website like "google" etc.
But when I tried to open specific site like my company PLM " Agile (https://agileplm.XXXX.com/Agile/default/login-cms.jsp)" throwing error
"The remote server machine does not exist or is unavailable"
I could open the web page on explorer but throwing error while executing from below line
Do Until .readyState = 4
DoEvents
Loop
Is this due to any protection over site or not?
I used early binding on this and created the object InternetExplorerMedium rather than InternetExplorer and it seemed to work.
The issue is that Internet Explorer disconnects from VBA (In my case some internal security settings). The solution is to reconnect Internet Explorer to VBA:
Include this code after the line IE is not responsive anymore and the existing Internet Explorer window will be assigned to = IEObject1
Dim shellWins As SHDocVw.ShellWindows
Dim explorer As SHDocVw.InternetExplorer
Set shellWins = New SHDocVw.ShellWindows
For Each explorer In shellWins
If explorer.Name = "Internet Explorer" Then
Set IEObject1 = explorer
Debug.Print explorer.LocationURL
Debug.Print explorer.LocationName
End If
Next
Set shellWins = Nothing
Set explorer = Nothing
If you have several IE windows open then this code picks the last one. You can choose between the windows by using the URL or LocationName if you need several open windows.
Try to make a test with example code below may help you to solve your issue.
Sub Automate_IE_Load_Page()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
'Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
'Set IE.Visible = True to make IE visible, or False for IE to run in the background
IE.Visible = True
'Define URL
URL = "https://agileplm.xxxx.com/Agile/default/login-cms.jsp"
'Navigate to URL
IE.Navigate URL
' Statusbar let's user know website is loading
Application.StatusBar = URL & " is loading. Please wait..."
' Wait while IE loading...
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.ReadyState = 4: DoEvents: Loop 'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
'Webpage Loaded
Application.StatusBar = URL & " Loaded"
'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
End Sub
Reference:
Automate Internet Explorer (IE) Using VBA
If your issue persist than try to provide a detailed information, Whether you are having issue with opening the page or you got an error while checking the ready state of IE. We will try to provide further suggestions.
Dim IE As Object
Dim doc As Object
Dim strURL As String
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.navigate "https://Google.com"
End With
For Each win In CreateObject("Shell.Application").Windows
If win.Name Like "*Internet Explorer" Then
Set IE = win: Exit For
End If
Next
With IE
Do Until .readyState = 4
DoEvents
Loop

Automatically uploading a picture file to a free online OCR resource

I am trying to upload a .jpg file to a free online OCR site. I am using Excel VBA for this project:
Sub getOcrText()
Dim ocrAddress As String: ocrAddress = "http://www.free-online-ocr.com"
Dim picFile As String: picFile = "C:\Users\310217955\Documents\pdfdown\test.jpg"
Dim elementCollection As Variant
Dim IE As New InternetExplorerMedium
With IE
.Visible = True
.Navigate (ocrAddress)
Do While IE.Busy: DoEvents: Loop
Set elementCollection = IE.document.getElementsByName("fileUpload")
End With
IE.Quit
Set IE = Nothing
End Sub
However, when I run the code to see whether I get objects to elementCollection I get a Runtime error, automation error, unspecified error, the code successfully navigates to the desired webpage.
How do I overcome this error?
You need to change a couple lines.
First this one:
Dim IE As Object: Set IE = CreateObject("InternetExplorer.Application")
.
The second problem...
IE.Busy is not a sufficient test. Make that line the following instead:
Do While (IE.Busy Or IE.READYSTATE <> 4): DoEvents: Loop

VBA - Addressing Internet Explorer tabs

Strangely enough I didn't find any information on the topic and I'm currently stuck at the point where I managed to open a new tab in an instance of IE by programmatically clicking a button, but I haven't the faintest clue of how to address the new tab in order to get information from there (the button basically brings up a new tab with the result of a search).
This is basically a straightforward question, but I'm including my code anyway:
Sub AddInfoFromIntranet()
Dim Ie As SHDocVw.InternetExplorer
Dim URL As String
Dim iFrames As MSHTML.IHTMLElementCollection
Dim iFrame As MSHTML.HTMLFrameElement
Dim Doc As MSHTML.HTMLDocument
Dim InputBox As MSHTML.IHTMLElementCollection, htmlButton, allTags, Tag
' Opens Intranet - yeah, sadly it's not a public web page
URL = "{My intranet website}"
Set Ie = New SHDocVw.InternetExplorer
With Ie
.navigate URL
.Visible = True
While .Busy Or .readyState <> READYSTATE_COMPLETE: DoEvents: Wend
Set Doc = .document
End With
' Gets top_window frame and navigates to it, then inserts the name to search
Set iFrames = Doc.getElementsByName("top_window")
If Not iFrames Is Nothing Then
Set iFrame = iFrames(0)
Ie.navigate URL & iFrame.src
While Ie.Busy Or Ie.readyState <> READYSTATE_COMPLETE: DoEvents: Wend
Set InputBox = Doc.getElementsByName("Nachnamevalue")
If Not InputBox Is Nothing Then InputBox(0).Value = "test"
' Clicks on "search"
Set allTags = Doc.getElementsByTagName("input")
For Each Tag In allTags
If Tag.Value = "suchen" Then
Tag.Click
Exit For
End If
Next
' Here a new tab is opened, must find info in this tab
While Ie.Busy Or Ie.readyState <> READYSTATE_COMPLETE: DoEvents: Wend
' HERE I HAVE NO CLUE WHAT TO WRITE. THE CODE ABOVE WORKS FLAWLESSLY
End If
Set Doc = Nothing
Set iFrames = Nothing
Set iFrame = Nothing
Set InputBox = Nothing
Set allTags = Nothing
Set Ie = Nothing
Ie.Quit
End Sub
Now, is there a way to address a tab by: 1) its name (and where do I find it) 2) its position in browser 3) the status (if it is "active") ?
Bonus questions: since I am new to VBA and Internet Explorer interaction, what exactly are the variables: htmlButton, allTags, Tag ? Also, could anyone explain if I need to set all the variables at the end to nothing, or I just need to set the Internet Explorer to nothing?
Thanks in advance!
See below for a function you can use to get an open IE document window - I don't think IE exposes any simple (VBA-accessible) API for working directly with tabs or determining whether a specific tab is active.
allTags is a collection of DOM elements with type "" , and Tag is a single memeber of that collection.
You do not have to set objects to Nothing before exiting a Sub (though some people still do that) - the VBA runtime will take care of that for you.
Sub TestGetIE()
Dim IE As Object
Set IE = GetIE("http://stackoverflow.com")
If Not IE Is Nothing Then
IE.document.execCommand "Print", False, 0
End If
End Sub
'Get a reference to an open IE window based on its URL
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
'check the URL and if it's the one you want then
' assign it to the return value
sURL = o.document.Location
On Error GoTo 0
'Debug.Print sURL
If sURL Like sLocation & "*" Then
Set retVal = o
Exit For
End If
Next o
Set GetIE = retVal
End Function

VBA access remote website, automate clicking submit after already automating clicking button on other webpage

I'm working with vba in excel 2010 and internet explorer 8 and Vista. The code below works to go to a remote website and post a form. On the resulting page, the code should click the "get estimates" button. Instead I get this error "object variable or with block variable not set". The highlighted problem line in the code is "estimate = ieApp.document.getElementById("btnRequestEstimates")".
I think part of the problem might be that the button that isn't working is a submit button that isn't part of a form. I am also wondering if the variables need to be reset before the 2nd button click. The error message implies this is a qualification problem, but I think it's a pretty standard way of qualifying an element in this situation. Those are some things I've been googling to no avail, I'm not really sure what the problem is.
Sub btn_version()
Dim ieApp As Object
Dim ieDoc As Object
Dim ieForm As Object
Dim ieObj As Object
Dim URL As String
Dim estimate As Object
URL = "http://www.craft-e-corner.com/p-2688-new-testament-cricut-cartridge.aspx"
Set ieApp = CreateObject("InternetExplorer.Application")
ieApp.Visible = True
ieApp.navigate URL
While ieApp.Busy Or ieApp.readyState <> 4: DoEvents: Wend
Set ieDoc = ieApp.document
Set ieForm = ieDoc.forms(1)
For Each ieObj In ieForm.Elements
If ieObj.ClassName = "AddToCartButton" Then
ieObj.Click
End If
Next ieObj
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
While ieApp.Busy Or ieApp.readyState <> 4: DoEvents: Wend
estimate = ieApp.document.getElementById("btnRequestEstimates")
estimate.submit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
End Sub
The code below combines your xmlhttp code from automate submitting a post form that is on a website with vba and xmlhttp (to give you better control on the POST, ie skipping your Set ieDoc = ieApp.document section in our question) with clicking the "btnRequestEstimates button on the final URl from this page
Sub Scrape2()
Dim objIE As Object
Dim xmlhttp As Object
Dim ieButton As Object
Dim strResponse As String
Dim strUrl As String
strUrl = "http://www.craft-e-corner.com/addtocart.aspx?returnurl=showproduct.aspx%3fProductID%3d2688%26SEName%3dnew-testament-cricut-cartridge"
Set objIE = CreateObject("InternetExplorer.Application")
objIE.navigate "about:blank"
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
'~~> Indicates that page that will receive the request and the type of request being submitted
xmlhttp.Open "POST", "http://www.craft-e-corner.com/addtocart.aspx?returnurl=showproduct.aspx%3fProductID%3d2688%26SEName%3dnew-testament-cricut-cartridge", False
'~~> Indicate that the body of the request contains form data
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
'~~> Send the data as name/value pairs
xmlhttp.Send "Quantity=1&VariantID=2705&ProductID=2688"
strResponse = xmlhttp.responseText
objIE.navigate strUrl
objIE.Visible = True
Do While objIE.readystate <> 4
DoEvents
Loop
objIE.document.Write strResponse
Set xmlhttp = Nothing
Set ieButton = objIE.document.getelementbyid("btnRequestEstimates")
ieButton.Click
End Sub