Excel VBA 2007 Performance Issue on Windows 7 (64 Bit) - excel

I am new to VBA. I have written a VBA code in Microsoft Excel 2007 to send a SOAP Message and Handle the soap Response.
I am reading the Soap Response and writing values to Excel cells in a loop.
The sample soap response is :-
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:getMyResponse xmlns:ns2="http://my.samplenamesapce/">
<return>
<col1>col1Value</col1>
<col2>col2Value</col2>
<col3>3.283E7</col3>
</return>
<return>
<col1>col1Value</col1>
<col2>col2Value</col2>
</return>
</ns2:getMyResponse>
</soap:Body>
</soap:Envelope>
and the VBA code to write response in cells is:
Private Sub getReportBtn_Click()
Dim WS As Worksheet: Set WS = Worksheets("my_report")
Dim request As New MSXML2.XMLHTTP60
Dim url As String
Dim response As New MSXML2.DOMDocument60
Dim requestData As String
'Clear the Report Sheet
WS.Range("A2:C65536").ClearContents
url = Range("url").Value
'Construct SOAP REQUEST
request.Open "POST", url, False
request.setRequestHeader "Content-Type", "text/xml; charset=""UTF-8"""
request.setRequestHeader "SOAPAction", ""
'Create SOAP REQUEST BODY
requestData = xmlBody
request.setRequestHeader "Content-Length", Len(requestData)
On Error GoTo err_handler:
'Send SOAP REQUEST
request.send requestData
'Read SOAP RESPONSE
response.LoadXML request.responseText
Dim MyReport As MSXML2.IXMLDOMNode
Dim MyReportList As MSXML2.IXMLDOMNodeList
Set MyReportList = response.getElementsByTagName("return")
Dim i As Integer
i = 1
For Each MyReport In MyReportList
i = i + 1
WS.Range("col1Range").Cells(i).Value = MyReport.selectSingleNode("col1").Text
WS.Range("col2Range").Cells(i).Value = MyReport.selectSingleNode("col2").Text
If MyReport.SelectNodes("col3").Length > 0 Then
WS.Range("col3Range").Cells(i).Value = MyReport.selectSingleNode("col3").Text
End If
Next MyReport
If i = 1 Then
MsgBox "No data found for requested query!"
Sheets("query").Select
Exit Sub
End If
Sheets("my_report").Select
Exit Sub
err_handler:
MsgBox "Error occurred during submission, please check your settings."
Exit Sub
End Sub
When I run My excel sheet on Windows 7(64 Bit), it is taking double amount of time as compared to running it on Windows XP (32 Bit) to process same data.
The configuration and physical location of both the machines are identical except the Operating system.

You might need to declare the variables as 32-bit variables. To see if the variable declaration is the area of delay, set timers at the start and end of the code and a third timer before your WS.range clearContents. My hunch is that assigning memory space is taking twice the time on the 64-bit machine.

Related

Why VBA Excel shows Error 91 for a definied variable?

As new coding maybe this question may be silly, but when I try to run this code, it keeps showing an Error 91 highlighting this line
'Get the number from the specified element on the page
number = html.getElementsByClassName("arial_14 redFont").Item(0).innerText
As I already identified number at the beginning, I have no idea why it keeps showing the variable wasn't defined.
Sub Get_Housing_Starts_From_Investing()
Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim website As String
Dim number As Variant
' Source: https://www.youtube.com/watch?v=IOzHacoP-u4
' Remember to activate References: Microsoft Office 16.0 Object Library, Microsoft HTML Object Library, Microsoft XML, v6.0, Visual Basic For Applications, Microsoft Excel 16.0 Object Library, OLE Automation
' Website to go to
website = "https://www.investing.com/economic-calendar/housing-starts-151"
' Create the object that will make the website request
Set request = CreateObject("Msxml2.ServerXMLHTTP.6.0")
' Where to go and how to go there - don´t need to change it
request.Open "GET", website, False
' Get fresh data
request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
' Send the request for the webpage
request.send
' Get the webpage response data into a variable
response = StrConv(request.responseBody, vbUnicode)
' Put the webpage into an html object to make data references easier
html.body.innerHTML = response
'Get the number from the specified element on the page
number = html.getElementsByClassName("arial_14 redFont").Item(0).innerText
' Output the number into a message box
MsgBox number
End Sub

vba run time error '- 2146697208 800c0008 )': the download of the specified resource has failed telegram

Request your help to solve the below issue,I am struck for two days,
vba run time error '- 2146697208 (800c0008 )': The download of the specified resource has failed
This is my code for your reference:
Sub telebot15status155555()
'Program Excel Messeger
' Purpose : Send Message to Telegram
' Author : John Eswin Nizar
' Date : 09 October 2017
Dim objRequest As Object
Dim strChatId As String
Dim strMessage1 As String
Dim strMessage2 As String
Dim strPostData As String
Dim strResponse As String
strChatId = "#messstatus"
strMessage1 = ""
strMessage2 = Now()
'strMessage = "hallo"
strPostData = "chat_id=" & strChatId & "&text=" & strMessage1 & strMessage2
Set objRequest = CreateObject("MSXML2.XMLHTTP")
With objRequest
.Open "POST", "https://api.telegram.org/sendMessage?", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (strPostData)
GetSessionId = .responseText
MsgBox GetSessionId
End With
End Sub
My advice here is to perform this API call in Chrome with DevTools open. Or access the page, where this happens, and find the Request on the 'Network' tab. Then look at the headers.
debug.print strPostData is returning:
chat_id=#messstatus&text=2/7/2020 9:40:23 AM
That format does not look correct for an API that is form-urlencoded. You need to see what the website is actually sending and receiving in the DevTools in order to replicate it.
IOW, The resource isn't found because the API is incorrectly formatted. From the base api, it looks like its actually a QueryString too because it ends with ? which might mean you have to url-encode format the POST Data into the QueryString for the main HTTP request. Have a look here: Pass Parameters in VBA HTTP Post Request

Excel VBA: get error code for invalid URL in hyperlink with WinHttpRequest

In Excel, I have a list with URLs. I need to check if IE (default browser) can open these. They don't have to open actually, it's to check the accessibility.
If they can't open, I need to isolate the error-code and place that in another column.
After searching around here, I started with following the hyperlinks, and used GET to get the data in a MsgBox. This seems to work partially, but of course now I get the MsgBox with every URL also without error. Also I'm looking for a way to extract the error and place that in the active sheet.
What I've got so far:
Sub Request_Data()
' declare
numRow = 2
Dim MyRequest As Object
' activate URLs without Follow
Do While ActiveSheet.Range("C" & numRow).Hyperlinks.Count > 0
numRow = numRow + 1
' create request
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", _
ActiveSheet.Range("C" & numRow)
' send request
MyRequest.Send
' outcome
MsgBox MyRequest.ResponseText
' isolate the error code (for example 404)
' place error code in excel sheet in column H next to row URL
Loop
End Sub
Does someone know how I should proceed?
I thought this might be useful but I don't know where to start.
Checking for broken hyperlinks in Excel
and
Bulk Url checker macro excel
Thanks in advance
See the code below - you will need to adapt the Test sub-routine to loop through your cells and call IsValidUrl for each value you want to test:
Option Explicit
Sub Test()
MsgBox IsValidUrl("http://www.thisdoesnotexistxxxxxxxxxxxxx.com/")
MsgBox IsValidUrl("http://www.google.com/")
MsgBox IsValidUrl("http://www.ppppppppppppqqqqqqqqqqqqqqrrrrrrrrrrrrr.com/")
End Sub
Function IsValidUrl(strUrl As String) As Long
Dim objRequest As Object
Dim lngCode As Long
On Error GoTo ErrHandler
Set objRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
With objRequest
.Open "GET", strUrl
.Send
lngCode = 0
End With
GoTo ExitHandler
ErrHandler:
lngCode = Err.Number
ExitHandler:
Set objRequest = Nothing
IsValidUrl = lngCode
End Function
My output is:
-2147012889
0
-2147012889

Excel VBA source code for extracting data from a URL

I want to extract the title of every news item displayed on "http://pib.nic.in/newsite/erelease.aspx?relid=58313" website using Excel VBA. I have written a code using getelementsbyclassname("contentdiv"). But the debugger is showing a error pertaining to that the object doesn't support...I want to extract the information items of every relid..which is there in the URL as well...
Cold scrapes like this are generally handled more efficiently with a XMLHTTP pull. This requires the addition of a few libraries to the VBE's Tools ► References. The code below needs Microsoft XML, v6.0, Microsoft HTML Object library and Microsoft Internet Controls. Might not need the last one but you probably will if you expand the code beyond what is supplied.
Public Const csURL As String = "http://pib.nic.in/newsite/erelease.aspx?relid=×ID×"
Sub scrape_PIBNIC()
Dim htmlBDY As HTMLDocument, xmlHTTP As MSXML2.ServerXMLHTTP60
Dim i As Long, u As String, iDIV As Long
On Error GoTo CleanUp
Set xmlHTTP = New MSXML2.ServerXMLHTTP60
Set htmlBDY = New HTMLDocument
For i = 58313 To 58313
htmlBDY.body.innerHTML = vbNullString
With xmlHTTP
u = Replace(csURL, "×ID×", i)
'Debug.Print u
.Open "GET", u, False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
.send
If .Status <> 200 Then GoTo CleanUp
htmlBDY.body.innerHTML = .responseText
For iDIV = 0 To (htmlBDY.getElementsByClassName("contentdiv").Length - 1)
If CBool(htmlBDY.getElementsByClassName("contentdiv")(iDIV).getElementsByTagName("span").Length) Then
Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = _
htmlBDY.getElementsByClassName("contentdiv")(iDIV).getElementsByTagName("span")(0).innerText
End If
Next iDIV
End With
Next i
CleanUp:
Set htmlBDY = Nothing
Set xmlHTTP = Nothing
End Sub
That should be enough to get you started. The site you are targeting requires that charset=UTF-8 be added to the request. I had no success without it. I strongly suspect that this may have been the source of your object doesn't support error.

Excel Web Query Object and Cookies: Is there a better way?

I have a HTML web page at work that I want to query data from tables into excel 2007. This web page requires I sign on with a password. I sign in with my normal IE7 browser, then I go to DATA -> connections -> my connections and edit the query. This reads the IE7 cookie cache and I re-POST the data to connect to the server's security by clicking "retry" when it says "the web query returned no data". After I do this, the data imports fine.
I can do this just fine and it only needs to be done once a day. Other users of my application find this difficult which leads to my question:
Is there a way to automatically POST this data back with VB? I'm thinking maybe I should use the cookie property of the IE.Document.cookie?
I'm calling the following login script, before I continue with the web query (set reference to XML library). Look around to find some instructions how you can find your POST parameters.
Sub XMLHttpLogin()
Dim i As Integer
Dim sExpr As String
Dim sPar As String, sURL as String
Dim sResp As String
Dim XMLHttp As MSXML2.XMLHTTP60
Set XMLHttp = New MSXML2.XMLHTTP60
sPar = "name=user1&pass=pass1&form_id=form1" 'The parameters to send.
sURL = "http://www.stackoverflow.com"
With XMLHttp
.Open "POST", sURL, True 'Needs asynchronous connection
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send (sPar)
i = 0 'wait until data has been downloaded
Do While i = 0
If .readyState = 4 Then
If .Status = 200 Then Exit Do
End If
DoEvents
Loop
sResp = .responseText 'contains source code of website
sExpr = "not-logged-in" 'look for this string in source code
If InStr(1, sResp, sExpr, vbTextCompare) Then
MsgBox "Not logged in. Error in XMLHttpLogin"
End If
End With
End Sub

Resources