Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88868

VBA Code for Saving a File that is the Target of a Hyperlink on a Web Page

$
0
0

I am trying to write some VBA code for what I thought should be a simple process. There are several links on an internal web page that, when clicked, will generate and then open a file in Excel. The issue lies in the fact that the URLs associated with the hyperlinks do not point to the files themselves since the files are generated at runtime. For example:

https://prodhost.company.com:45443/org/exportAdvancedSearchToXLS?f=worldRegion|worldRegion|worldRegion&v=NA|EMEA|APAC&e=%3D|%3D|%3D&qName=All%20Global%20Employees

I need a way to save the file generated by the hyperlink to my local machine before performing additional operations on it. Essentially, I am looking to automate what right-clicking on the hyperlink and selecting "Save target as..." will do.

The following code (provided by KittyKat) will save the generated file to my local machine but when I try to open the file, Excel is not able to recognize the format and generates the error "Excel cannot open the file 'test.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

Sub DownloadFile()
    Dim WinHttpReq As Object
    Dim oStream As Object
    Dim myURL As String
    Dim LocalFilePath As String

    LocalFilePath = "C:\Temp\test.xlsx"

    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", gsADDRESS, False, "", ""'("username", "password")
    WinHttpReq.send

    If WinHttpReq.Status = 200 Then
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.responseBody
        oStream.SaveToFile LocalFilePath, 2
        oStream.Close
    End If
End Sub

I have tried saving the file as an .XLSX and .XLSB file but to no avail.


Viewing all articles
Browse latest Browse all 88868


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>