I've looked at dozens of similar topics here without finding what I'm looking for. If I was doing it manually, I would navigate to the URL, given some parameters:
When I go there, it requests a username and password in a pop-up box, which I enter, and it downloads the CSV.
This Python code works perfectly:
import requests
from requests.auth import HTTPBasicAuth
USERNAME = "i_cant_tell_you_guys"
PASSWORD = "definitely_cant_share_this"
auth = HTTPBasicAuth(USERNAME, PASSWORD)
URL = "https://the.website.com/mobile/rest/reportservice/exportReport?name=shared%2FMV+Report.ppr&format=csv&showTotals=false&valueDate=Today"
resp = requests.get(URL.format(USERNAME, PASSWORD), auth=auth, verify=False)
print resp.content
But I can't seem to replicate it in VBA. Is it possible? If not, could I have Excel and Python work together somehow?
Thanks!
Edit: Several people suggested this approach: VBA WinHTTP to download file from password proteced https website but since the URL I'm pulling isn't the actual file URL, it won't work.
Edit: Finally got it working. The website had a certificate mismatch, so I had to tell WinHTTP to ignore SSL errors. Here's the new code:
Sub SaveFileFromURL()
Const Option_SSLErrorIgnoreFlags = 4
Const SslErrorFlag_Ignore_All = 13056
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Dim FileNum As Long
Dim FileData() As Byte
Dim WHTTP As Object
mainUrl = "https://website.com"
fileUrl = "https://website.com/myfile.csv"
filePath = "C:\myfile.csv"
myuser = "login"
mypass = "pass"
Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
WHTTP.Open "POST", mainUrl, False
WHTTP.SetCredentials myuser, mypass, HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
WHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
WHTTP.Option(Option_SSLErrorIgnoreFlags) = SslErrorFlag_Ignore_All
WHTTP.Send
WHTTP.Open "GET", fileUrl, False
WHTTP.Send
FileData = WHTTP.ResponseBody
Set WHTTP = Nothing
FileNum = FreeFile
Open filePath For Binary Access Write As #FileNum
Put #FileNum, 1, FileData
Close #FileNum
MsgBox "File has been saved!", vbInformation, "Success"
End Sub
Now I'm getting "Run-time error '75': Path/File access error"