vba excel sms for api - vba

I would like that every time I register an appointment, the client is notified by sms.
You will find attached a vba code for this purpose for sending sms.
The script seems to be executing.
On the other hand, do not deliver the sms as expected.
Someone to help me figure out what is missing please
Sub send_SMS_RDV()
Application.ScreenUpdating = False
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''essai code xfactor'''''''''''''''''''''
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim Recipient As String
Dim Message As String
Dim rowname As String
Dim rowprestardv As String
Dim rowtimerdv, rownumber, rowdaterdv, x As String
rowtimerdv = Worksheets("PLANNING").Range("I4").Value
rowprestardv = Worksheets("PLANNING").Range("H4").Value
rowname = Worksheets("PLANNING").Range("N4").Value
rownumber = Worksheets("PLANNING").Range("O4").Value
rowdaterdv = Worksheets("PLANNING").Range("Q4").Value
x = "237"
Recipient = "x&lastrownumber"
'
If rowdaterdv = Worksheets("PLANNING").Range("P32").Value Then
'
Message = "Dear " & rowname & ", your appointment has been register at : " & rowtimerdv & " Contact us for any changes. Merci"
Else
'
Message = "Dear " & rowname & ", your appointment has been register at : " & rowdaterdv & " Contact us for any changes. Merci"""
'
'
End If
'Set vars where phone numbers and msg are set in your sheet'
URL = api.smsfactor.com/send?text=" + Message + "&to=" + Recipient
objHTTP.Open "GET", URL, False
objHTTP.SetRequestHeader "Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzNDcwOSIsImlhdCI6MTYwMTk5NzM4N30.VbWdRwVwtIn5JtwNYjeJ8imnM_2bYskRIg2O6uZG5fA" 'Your Token'
objHTTP.SetRequestHeader "Accept", "application/json"
objHTTP.send ("")
End Sub

Your URL variable looks wrong. That would need to be a string but it's not a proper string. You are missing a start quote mark and you are using + for concatenation where I would expect to see & instead.
Try changing it to this:
URL = "api.smsfactor.com/send?text=" & Message & "&to=" & Recipient

Thank you for your contribution.
I solved the problem.
here is what I modified to make it work.
Recipient = 237 & rownumber
and after url
url = Replace(url, " ", "%20")
However, I would like to configure with another provider but have problems again
Sub send_SMS_Fact()
Application.ScreenUpdating = False
' Declaring varibles for sending sms
Dim objWinHTTP As Object
Dim response, send As String
Dim sURL As String
Dim API As String
Dim SenderID As String
Dim Recipient, Message As String
' Declaring varibles for Application
Dim rowname As String
Dim rowtypevente As String
Dim rowamount, rownumber, x As String
Worksheets("FACTURATION").Activate
rowtypevente = Worksheets("FACTURATION").Range("H11").Text
rowamount = Worksheets("FACTURATION").Range("M11").Text
rowname = Worksheets("FACTURATION").Range("S11").Text
rownumber = Worksheets("FACTURATION").Range("T11").Text
API = "Um9kcnlnMTIzOnNhbG9tZQ=="
x = "237"
Recipient = x & rownumber
SenderID = "TechSoft-SMS"
' Preparation sms
If rowtypevente = "VENTE DIFF" Then
Message = "Dear " & rowname & ", The amount of your invoice which is: " & rowamount & " remains to be paid as soon as possible"
Else
rowtypevente = "VENTE"
Message = "Dear " & rowname & ", We thank you for your loyalty and hope to have satisfied you. Best regards and see you soon"
End If
' Checking for valid mobile number
If rownumber <> "700000000" Then
Else
Recipient = CStr(rownumber)
End If
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''test protocole url'''''
Set objWinHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
sURL = app.techsoft-web-agency.com/sms/api"
sURL = Replace(sURL, " ", "%20")
Request = "&apikey=" & API & URLEncode(Apikey) & "&number=" & Recipient & URLEncode(Number)
Request = Request & "&message=" & Message & URLEncode(Message)
Request = Request & "&expediteur=" & SenderID & URLEncode(Expediteur) & "&msg_id=" & MsgID
objWinHTTP.Open "GET", URL & Request, False
objWinHTTP.SetTimeouts 30000, 30000, 30000, 30000
objWinHTTP.send
If objWinHTTP.StatusText = "OK" Then
strReturn = objWinHTTP.ResponseText
Debug.Print strReturn
End If
Set objWinHTTP = Nothing
send = strReturn
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function URLEncode(sRawURL) As String
On Error GoTo Catch
Dim iLoop As Integer
Dim sRtn As String
Dim sTmp As String
Const sValidChars = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz:/.?=_-$()~&"
If Len(sRawURL) > 0 Then
For iLoop = 1 To Len(sRawURL)
sTmp = Mid(sRawURL, iLoop, 1)
If InStr(1, sValidChars, sTmp, vbBinaryCompare) = 0 Then
sTmp = Hex(Asc(sTmp))
If sTmp = "20" Then
sTmp = "+"
ElseIf Len(sTmp) = 1 Then
sTmp = "%0" & sTmp
Else
sTmp = "%" & sTmp
End If
End If
sRtn = sRtn & sTmp
Next iLoop
URLEncode = sRtn
End If
Finally:
Exit Function
Catch:
URLEncode = ""
Resume Finally
End Function
This is how I configured the new url according to the documentation I found on their site.
But at the line "objWinHTTP.Open" GET ", URL & Request, False" I am told that the url uses an unrecognized protocol

Related

Error 3000 Using VBA and HCL ( Lotus) notes

I made a code to send some emails, using HCL NOTES and Excel, but I have been stuck.
ERROR 3000 appears when going through the line ".SEND 0, vaRecipient". I think what happens is that the connection with the database is lost, after going through the procedure of attaching an image to the body of the mail. Since if I remove those lines of code, no error arises.
Sub SendQuoteToEmail()
Dim NSession As Object
Dim NDatabase As Object
Dim NUIWorkSpace As Object
Dim NDoc As Object
Dim NUIdoc As Object
Dim NRichTextItem As Object
Dim NrichTextHeader As Object
Dim NMimeImage As Object
Dim strImageType As String
Dim WordApp As Object
Dim EmbedObj As Object
Dim Body As Object
Dim NStream As Object
Dim Subject As String
Dim MailAddress As String
Dim MailAddressCC As String
Dim MailAddressCC2 As String
Dim MailAddressCCO As String
Dim MailAddressCCO2 As String
Dim AttchFiles1, AttchFiles2, AttchFiles3, AttchFiles4 As String
Dim AddImage As String
Dim pf As Integer
Dim Uf As Integer
Dim x As Double
'On Error Resume Next
Set a = ThisWorkbook.Sheets("Base Emails")
pf = 4
Uf = 0
Do While Uf = 0
cuit = Range("a" & pf).Value
If cuit <> Empty Then
Subject = UserForm1.SubjectBox & a.Cells(pf, "D") & " - CUIL N°: " & a.Cells(pf, "A") '
MailAddress = a.Cells(pf, "F")
MailAddressCC = UserForm1.TextBoxCC
MailAddressCC2 = UserForm1.TextBoxCC2
MailAddressCCO = UserForm1.TextBoxCCO
MailAddressCCO2 = UserForm1.TextBoxCCO2
Set NSession = CreateObject("Notes.NotesSession")
Set NUIWorkSpace = CreateObject("Notes.NotesUIWorkspace")
Set NDatabase = NSession.GETDATABASE("", "")
If Not NDatabase.IsOpen Then NDatabase.OPENMAIL
Set NDoc = NDatabase.CREATEDOCUMENT
With NDoc
.SendTo = MailAddress
.CopyTo = MailAddressCC & ", " & MailAddressCC2
.Subject = Subject
.Body = UserForm1.FirstLineBox & vbLf & vbLf & _
UserForm1.FirstParagraphBox & vbLf & vbLf & _
UserForm1.SecondParagraphBox & vbLf & vbLf & _
UserForm1.ThirdParagraphBox & vbLf
.SAVEMESSAGEONSEND = True
End With
AddImage = ThisWorkbook.Path & "\Image\" & Worksheets("Files").Range("A" & 5)
If AddImage <> "" Then
Set NStream = NSession.CREATESTREAM
Call NStream.Open(AddImage)
Set Body = NDoc.CreateMIMEEntity("memo")
Set richTextHeader = Body.CreateHeader("Content-Type")
Call richTextHeader.SetHeaderVal("multipart/mixed")
Set mimeImage = Body.CreateChildEntity()
strImageType = "image/jpeg; image/gif" '" Other formats are "image/gif" "image/bmp" -
Call mimeImage.SetContentFromBytes(NStream, strImageType, ENC_IDENTITY_BINARY)
Call NStream.Close
End If
AttchFiles1 = ThisWorkbook.Path & "\Files\" & Worksheets("Files").Range("A" & 1)
If AttchFiles1 <> "" Then
Set AttachMe = NDoc.CREATERICHTEXTITEM("Attachment1")
Set EmbedObj = AttachMe.EmbedObject(1454, "", AttchFiles1, "Adjunto")
End If
AttchFiles2 = ThisWorkbook.Path & "\Files\" & Worksheets("Files").Range("A" & 2)
If AttchFiles2 <> "" Then
Set AttachMe = NDoc.CREATERICHTEXTITEM("Attachment2")
Set EmbedObj = AttachMe.EmbedObject(1454, "", AttchFiles2, "Adjunto")
End If
AttchFiles3 = ThisWorkbook.Path & "\Files\" & Worksheets("Files").Range("A" & 3)
If AttchFiles3 <> "" Then
Set AttachMe = NDoc.CREATERICHTEXTITEM("Attachment3")
Set EmbedObj = AttachMe.EmbedObject(1454, "", AttchFiles3, "Adjunto")
End If
AttchFiles4 = ThisWorkbook.Path & "\Files\" & Worksheets("Files").Range("A" & 4)
If AttchFiles4 <> "" Then
Set AttachMe = NDoc.CREATERICHTEXTITEM("Attachment4")
Set EmbedObj = AttachMe.EmbedObject(1454, "", AttchFiles4, "Adjunto")
End If
With NDoc
.PostedDate = Now()
.SEND 0, vaRecipient '<--- ERROR 3000
End With
Set NStream = Nothing
Set NDoc = Nothing
Set WordApp = Nothing
Set NSession = Nothing
Set EmbedObj = Nothing
pf = pf + 1
Else
Uf = 1
Exit Do
End If
Loop
VbMessage = "Sent messages"
Call Clean
End Sub
If I remove these lines of code, the procedure works. So I suppose that by manipulating "NSession", something happens, but I don't know what.
AddImage = ThisWorkbook.Path & "\Image\" & Worksheets("Files").Range("A" & 5)
If AddImage <> "" Then
Set NStream = NSession.CREATESTREAM
Call NStream.Open(AddImage)
Set Body = NDoc.CreateMIMEEntity("memo")
Set richTextHeader = Body.CreateHeader("Content-Type")
Call richTextHeader.SetHeaderVal("multipart/mixed")
Set mimeImage = Body.CreateChildEntity()
strImageType = "image/jpeg; image/gif" '" Other formats are "image/gif" "image/bmp" -
Call mimeImage.SetContentFromBytes(NStream, strImageType, ENC_IDENTITY_BINARY)
Call NStream.Close
End If
You've got two pieces of incompatible code here.
.Body = UserForm1.FirstLineBox & vbLf & vbLf & _
UserForm1.FirstParagraphBox & vbLf & vbLf & _
UserForm1.SecondParagraphBox & vbLf & vbLf & _
UserForm1.ThirdParagraphBox & vbLf
And
Set Body = NDoc.CreateMIMEEntity("memo")
Set richTextHeader = Body.CreateHeader("Content-Type")
Call richTextHeader.SetHeaderVal("multipart/mixed")
Set mimeImage = Body.CreateChildEntity()
strImageType = "image/jpeg; image/gif" '" Other formats are "image/gif" "image/bmp" -
Call mimeImage.SetContentFromBytes(NStream, strImageType, ENC_IDENTITY_BINARY)
You can't work with the message body both as Notes rich text (the first piece of code) and as MIME. You need to pick one or the other. I'm guessing you're going to pick MIME, in which case you are going to need to create a text/plain part and populate it with your three paragraphs of text.

Sending sms with excel vba

I have a working excel vba program, which allows to invoice the services and to take the appointments of the customers. I would like that each time an invoice is issued, the customer receives a thank you message for the amount of the invoice by sms. Also when a client's appointment is recorded, he gets an acknowledgment of receipt.
A similar problem has already been dealt with here. However there are items below that I did not understand in this code.
My knowledge of vba is really basic. Can you help me please.
Below is the code, in bolt and italic the lines which I don't understand.
thank you in advance.
Sub send_SMS***(xyz As Integer)***
Application.ScreenUpdating = False
' Declaring varibles for sending sms
Dim HttpReq As New WinHttpRequest
Dim response As String
Dim sURL As String
Dim smsto, smstext As String
' Declaring varibles for Application
***Dim lastrow, lastrow1, lastrow2, x, pointe As Long
lastrow = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row
lastrow1 = Sheets(2).Range("A" & Rows.Count).End(xlUp).Row
lastrow2 = Sheets(3).Range("A" & Rows.Count).End(xlUp).Row***
' Caculation of red card points
If xyz = 1 Then
pointe = (***frmmain.txtpointe.Value*** - frmmain.txtpointr.Value) + (*frmmain.txtamount.Value* * 10 / 100)
smstext = "Dear Member, You have reedemed " & frmmain.txtpointr.Text & " red points and your balance is " & pointe & " points"
Else
pointe = frmmain.txtpointe.Value + (frmmain.txtamount.Value * 10 / 100)
If pointe >= 1000 Then
smstext = "Dear Member, You have reached " & pointe & " red points and you can reedem it your next visit"
Else
smstext = "Dear Member, Your bill amount is " & frmmain.txtinvoice.Text & " and your Red Point balance is " & pointe & " Points"
End If
End If
' Checking for valid mobile number
If Len(frmmain.lblmobile.Caption) < 10 Then
Call nomobile(pointe)
Else
smsto = CStr(frmmain.lblmobile.Caption)
' //another way to create the HttpReq
Set HttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
' // API for sending sms
sURL = "https://malert.in/api/api_http.php?username=username&password=password&senderid=REDHCP&to=" & smsto & "&text=" & smstext & "&route=Enterprise&type=text"
' Debug.Print sURL
On Error Resume Next
With HttpReq
.Open "GET", sURL, False
.send
End With
response = HttpReq.responseText
HttpReq.waitForResponse
' MsgBox Left(response, 2)
Debug.Print response
If Left(response, 2) = "OK" Then
Call nomobile(pointe)
Else
Call errorconnection(smstext, pointe)
End If
End If
sURL = "https://malert.in/api/api_http_balance.php?username=username&password=password&route=Enterprise"
' Debug.Print sURL
On Error Resume Next
With HttpReq
.Open "GET", sURL, False
.send
End With
response = HttpReq.responseText
HttpReq.waitForResponse
frmmain.lblstatus.Caption = response
Debug.Print response
Application.ScreenUpdating = True
End Sub
Thank

How to debug a macro that calculates distances between two points?

I have a macro that calculates distances between two points. I am unable to get it to work, and would like some help debugging it.
I have created a Google API key, and have incorporated that in as well, but for some reason the macro doesn't work
Public Function
GetDT(origin_city As String, _
origin_state As String, origin_country As String, _
destination_city As String, _
destination_state As String, destination_country As String _
)
Dim surl As String
Dim oXH As Object
Dim bodytxt As String
Dim distanc_e As String
surl = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="
& _
Replace(origin_city, " ", "+") & "+" & Replace(origin_state, " ", "+") &
"+" & Replace(origin_country, " ", "+") & _
"&destinations=" & _
Replace(destination_city, " ", "+") & "+" & Replace(destination_state, "
", "+") & "+" & Replace(destination_country, " ", "+") & _
"&mode=driving&units=metric&key=MY_KEY"
Set oXH = CreateObject("msxml2.xmlhttp")
With oXH
.Open "get", surl, False
.send
bodytxt = .responseText
End With
bodytxt = Right(bodytxt, Len(bodytxt) - InStr(1, bodytxt, "<text>") - 5)
tim_e = Left(bodytxt, InStr(1, bodytxt, "</text>") - 1)
bodytxt = Right(bodytxt, Len(bodytxt) - InStr(1, bodytxt, "<text>") - 5)
distanc_e = Left(bodytxt, InStr(1, bodytxt, "</text>") - 1)
GetDT = distanc_e
Set oXH = Nothing
End Function
There is no way to confidently answer this question with the information provided. Writing a separate function to create the url will make your code more testable. Using Option Explicit to force all variables to be declared will detect any typos.
If MY_KEY is a variable then the url should look like this "..metric&key=" & MY_KEY.
surl = GetDTURL(origin_city, origin_state, origin_country, destination_city, destination_state, destination_country)
Function GetDTURL(origin_city As String, origin_state As String, origin_country As String, destination_city As String, destination_state As String, destination_country As String)
Dim surl As String
Const BaseURl As String = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins=#origin_city+#origin_state+#origin_country&destinations=#destination_city+#destination_state+#destination_country&mode=driving&units=metric&key=MY_KEY"
surl = BaseURl
surl = Replace(surl, "#origin_city", origin_city)
surl = Replace(surl, "#origin_state", origin_state)
surl = Replace(surl, "#origin_country", origin_country)
surl = Replace(surl, "#destination_city", destination_city)
surl = Replace(surl, "#destination_state", destination_state)
surl = Replace(surl, "#destination_country", destination_country)
surl = Replace(surl, " ", "+")
GetDTURL = surl
End Function

Yahoo Finance Cookie Crumb no longer working

I have a VBA macro that I found somewhere on the internet last year after they changed their API around Q2 2017. It looks like they might have changed it again as when I run it all I get is:
Error: ZNGA
Details: {
"finance": {
"error": {
"code": "Unauthorized",
"description": "Invalid cookie"
}
}
}
For every ticker.
I'm looking at the Sub where crumb and cookie are established which is the following:
Sub BSRawData()
Dim sURL As String, sResult, strSQL As String
Dim oResult As Variant, oData As Variant, r As Long, c As Long, period1 As Double, period2 As Double
Dim db As Database
Dim rst As Recordset
Dim lastRow, recs, i, i2 As Integer
Dim baseDate As Date
Dim startDate As Date
Dim finalDate As Date
Dim crumb As String, cookie As String, validCookieCrumb As Boolean
' Load the ticker symbol into a recordset for iteration
Set db = CurrentDb
Set rst = db.OpenRecordset("SELECT DISTINCT Ticker FROM clients WHERE Ticker IS NOT NULL ORDER BY Ticker DESC;")
'Debug.Print (rst.RecordCount)
recs = rst.RecordCount
rst.MoveFirst
For i = 1 To recs
For i2 = 1 To 2
ExcelObject
Call getCookieCrumb(crumb, cookie, validCookieCrumb)
' Date ranges, do not need to touch the first one
baseDate = #1/1/1970#
startDate = #5/2/2017#
finalDate = #5/1/2018#
' Calculate the number of seconds
period1 = (startDate - baseDate) * 86400
period2 = Round((finalDate - baseDate + 0.33333333) * 86400)
' The first time through it fetches the 52-week data which does not contain dividends. The second time through it fetches dividends only.
If i2 = 1 Then
' Construct the URL string
sURL = "https://query1.finance.yahoo.com/v7/finance/download/" & rst!Ticker & "?period1=" & period1 & "&period2=" & period2 & "&interval=1wk&events=history&crumb=" & crumb
Else
' Construct the URL string
sURL = "https://query1.finance.yahoo.com/v7/finance/download/" & rst!Ticker & "?period1=" & period1 & "&period2=" & period2 & "&interval=1wk&events=div&crumb=" & crumb
End If
' Debug.Print "URL: " & sURL
' Pass the URL into the GetHTTPResult function
sResult = GetHTTPResult(sURL, cookie)
' Takes the result from the function and iterates through it, putting it into Excel
If sResult Like "*Error*" Then
Debug.Print ("Error: " & rst!Ticker)
Debug.Print ("Details: " & sResult)
xl.ActiveWorkbook.Close False
xl.Quit
GoTo NextRecord
End If
oResult = Split(sResult, vbLf)
' Debug.Print "Lines of result: " & UBound(oResult)
For r = 0 To UBound(oResult)
oData = Split(oResult(r), ",")
For c = 0 To UBound(oData)
If oData(UBound(oData)) <> "Null" Then
xl.ActiveSheet.Cells(r + 1, c + 1) = oData(c)
End If
Next c
Next r
Set oResult = Nothing
' Find and replace 'Date' with 'Week' to clear up reserved work complications
xl.Application.DisplayAlerts = False
xl.Cells.Replace What:="Date", Replacement:="Week", LookAt:=xlPart
xl.Application.DisplayAlerts = True
' Insert column and add ticker symbol. won't go into access without it since it is the primary key and indexed
xl.Columns("A").Insert Shift:=xlRight
xl.Range("A1").Value = "Ticker"
lastRow = xl.Cells(xl.Rows.Count, "B").End(xlUp).Row
xl.Range("A2:A" & lastRow).Value = rst!Ticker
' Save the file and close Excel
xl.Application.DisplayAlerts = False
xl.ActiveWorkbook.SaveAs fileName:="C:\Black-Scholes\temp.xlsx"
xl.Application.DisplayAlerts = True
xl.ActiveWorkbook.Close False
xl.Quit
' Go to next record if there were no dividends
If lastRow = 1 Then
GoTo NextRecord
End If
' Back to Access to delete records from the table if ticker is already in there
If i2 = 1 Then
DoCmd.SetWarnings False
strSQL = "DELETE * FROM blackscholes_raw_data WHERE Ticker = '" & rst!Ticker & "';"
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
End If
' Back to Access to import
DoCmd.TransferSpreadsheet acImport, TableName:="blackscholes_raw_data", fileName:="C:\Black-Scholes\temp.xlsx", HasFieldNames:=True
Next i2
NextRecord:
' On to the next record
rst.MoveNext
Next i
' Move dividends to the week they correspond to and delete row
DoCmd.SetWarnings False
strSQL = "UPDATE blackscholes_raw_data t1 " & _
"LEFT JOIN blackscholes_raw_data t2 " & _
"ON t1.Ticker = t2.Ticker " & _
"SET t1.Dividends = t2.Dividends " & _
"WHERE t1.Dividends IS NULL AND t2.Dividends IS NOT NULL AND t2.Week BETWEEN t1.Week AND t1.Week + 6;"
DoCmd.RunSQL strSQL
strSQL = "DELETE * FROM blackscholes_raw_data WHERE Open IS NULL;"
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
MsgBox "Done."
End Sub
Sub getCookieCrumb(crumb As String, cookie As String, validCookieCrumb As Boolean)
Dim i As Integer
Dim str As String
Dim crumbStartPos As Long
Dim crumbEndPos As Long
Dim objRequest
validCookieCrumb = False
For i = 0 To 5 'ask for a valid crumb 5 times
Set objRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
With objRequest
.Open "GET", "https://finance.yahoo.com/lookup?s=bananas", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
.send
.waitForResponse (10)
cookie = Split(.getResponseHeader("Set-Cookie"), ";")(0)
crumbStartPos = InStr(1, .responseText, """CrumbStore"":{""crumb"":""", vbBinaryCompare) + Len("""CrumbStore"":{""crumb"":""")
crumbEndPos = InStr(crumbStartPos, .responseText, """", vbBinaryCompare)
crumb = Mid(.responseText, crumbStartPos, crumbEndPos - crumbStartPos)
End With
If Len(crumb) = 11 Then 'a valid crumb is 11 characters long
validCookieCrumb = True
Exit For
End If:
' If i = 5 Then ' no valid crumb
' validCookieCrumb = False
' End If
Next i
End Sub
Function GetHTTPResult(sURL As String, cookie As String) As String
Dim strUrl, sResult As String
Dim http As WinHttp.WinHttpRequest
Set http = New WinHttp.WinHttpRequest
' Uncomment the line directly below if you need to get a new crumb and cookie
' sURL = "https://finance.yahoo.com/lookup?s=%7B0%7D"
' strCookie = "B=bnnkr99cklnh9&b=3&s=69"
With http
.Open "GET", sURL, False
.setRequestHeader "Cookie", cookie
.send
.waitForResponse
' Debug.Print (http.responseText)
' Debug.Print "Status: " & http.Status & " - " & http.statusText
sResult = .responseText
Set http = Nothing
GetHTTPResult = sResult
End With
End Function
What it should do is import the table on this link into Excel and then import it into Access.
https://finance.yahoo.com/quote/AAPL/history?period1=1503558000&period2=1535094000&interval=1wk&filter=history&frequency=1wk
I'm using Postman to send GET requests to the API. The response header does not contain "Set-Cookie", nor any mention of ""CrumbStore"". The VBA does return values for "Set-Cookie" and a few other things I wouldn't expect it to, so don't quite understand that.
Anyone encountered this yet and have a solution?
Ok, pretty simple fix actually.
This line:
.Open "GET", "https://finance.yahoo.com/lookup?s=bananas", False
Just needed to be changed to a valid ticker. So for my needs I did:
.Open "GET", "https://finance.yahoo.com/quote/AAPL/history?period1=1503558000&period2=1535094000&interval=1wk&filter=history&frequency=1wk", False
Apparently, it used to return a valid crumb by just looking up anything, whether or not the ticker was good. Now doing so doesn't return CrumbStore, so there isn't anything to find.
Disable row with (')
cookie = Split(.getResponseHeader("Set-Cookie"), ";")(0)
and write:
cookie = "thamba"
(If not run, find setCookie in finance yahoo site)

Whitelist all subdomains VBA macro

I have implemented a macro to append a string before any hyperlinks in an outlook email. however, I put a domain whitelist which is working fine for example if I whitelist https : //google.com then it will whitelist it in addition to https : //google.com/etc.. and anything that follows it.
My problem is if someone wants to visit https://mail.google.com or any other subdomain it will not work and will append it to be APPEND_THIS_https://mail.google.com. How can I allow all subdomains to be in the whitelist?
Dim myStr As String
Dim myURL As String
' Declare whitlist URL variables
'Dim whiteURL01 As String
'Dim whiteURL02 as string
myURL = "APPEND_THIS_"
' Add URLs to whitelist here
whiteURL01 = "https://google.com"
' Store the HTML Bodyin a variable
myStr = Msg.htmlbody
' Update all URLs
myStr = Replace(myStr, "href=""", "a href=" & myURL, , , vbTextCompare)
' Process whitelist
myStr = Replace(myStr, myURL & whiteURL01, whiteURL01, , , vbTextCompare)
' Assign back to HTML Body
Msg.htmlbody = myStr
' Save the mail
Msg.Save
Here is how I would do it. I added an extra loop to look thru the entire message body in case there are several loops.
Dim myStr As String
Dim myURL As String
Dim white_url_found As Boolean
myStr=Msg.HTMLBody
myURL = "APPEND_THIS_"
Dim whiteURL(0 To 2) As String
whiteURL(0) = ".google.com"
whiteURL(1) = ".facebook.com"
whiteURL(2) = "mailto:"
searchstart = InStr(1, myStr, "href=")
While searchstart <> 0
nextstart = InStr(searchstart + 1, myStr, "href=")
white_url_found = False
For i = LBound(whiteURL()) To UBound(whiteURL())
URL_pos = InStr(searchstart, myStr, whiteURL(i))
If URL_pos > 0 And (URL_pos < nextstart Or nextstart = 0) Then
white_url_found = True
Exit For
End If
Next i
If Not white_url_found Then
myStr = Left(myStr, searchstart - 1) & Replace(myStr, "href=" & Chr(34), "href=" & Chr(34) & myURL, searchstart, 1, vbTextCompare)
If nextstart <> 0 Then nextstart = nextstart + Len(myURL)
End If
searchstart = nextstart
Wend
Msg.HTMLBody = myStr
Msg.Save