簡體   English   中英

VBA:在JavaScript鏈接后下載文件

[英]VBA: Downloading a file behind JavaScript link

如何編寫VBA代碼以下載位於JavaScript鏈接后面的文件? 關於如何使用VBA從特定鏈接下載文件的資源很多,但是沒有資源顯示如何在JavaScript鏈接后面下載文件。

例如,如何在此網站的“導出到電子表格”后面下載文件: https : //www.vanguardinvestments.com.au/retail/ret/investments/product.html#/fundDetail/wholesale/portId=8101/ assetCode =權益/價格

我們仍然聲明並使用urlmon嗎?

'Declaration of API function for Office 2010+
Private Declare PtrSafe Function URLDownloadTOFile Lib "urlmon" Alias         
"URLDownloadToFileA" ( _
    ByVal pCaller As LongPtr, _
    ByVal sZURL As String, _
    ByVal szFileName As String, _
    ByVal dwReserved As LongPtr, _
    ByVal lpfnCB As LongPtr _
) As LongPtr

#Else
'Declaration of API function for pre Office 2010 versions
Private Declare Function URLDownloadTOFile Lib "urlmon" Alias 
"URLDownloadToFileA" ( _
    ByVal pCaller As Long, _
    ByVal sZURL As String, _
    ByVal szFileName As String, _
    ByVal dwReserved As Long, _
    ByVal lpfnCB As Long _
) As Long
#End If

Sub DownloadOneFile()
    Dim FileURL As String
    Dim DestinationFile As String

    'How do you modify this to handle a javascript link?
    FileURL = "https://www.vanguardinvestments.com.au/retail/ret/investments/product.html#/fundDetail/wholesale/portId=8101/assetCode=equity/?prices"
    DestinationFile = "C:\VBA\prices.csv"

    URLDownloadToFile 0, FileURL, DestinationFile, 0, 0

End Sub

這將觸發該事件。 感謝@Greedo的原理是通過循環直到窗口中可見指定的元素來等待頁面加載。 對不起,可怕的發送密鑰。

Public Sub DownloadFile()

    Dim objIE As InternetExplorer, currPage As HTMLDocument, url As String
    url = "https://www.vanguardinvestments.com.au/retail/ret/investments/product.html#/fundDetail/wholesale/portId=8101/assetCode=equity/?prices"
    Set objIE = New InternetExplorer
    objIE.navigate url
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    Set currPage = objIE.document
    objIE.Visible = True
    Dim myDiv As HTMLDivElement: Set myDiv = currPage.getElementById("price-distribution")
    Dim elemRect As IHTMLRect: Set elemRect = myDiv.getBoundingClientRect
    Do Until elemRect.bottom > 0
        currPage.parentWindow.scrollBy 0, 10000
        Set elemRect = myDiv.getBoundingClientRect
    Loop

    objIE.document.getElementsByClassName("export_icon hideOnSml ng-binding")(0).FireEvent "onclick"

    Application.SendKeys "%{S}"

End Sub

如有必要,您可以在發送鍵之前添加以下內容,以確保窗口已打開,但目前仍可以正常工作。

    Dim objShell As Shell
    Set objShell = New Shell

    Application.Wait Now + TimeSerial(0, 0, 10) 'alter to give enough time for window
    For Each objIE In objShell.Windows
        If TypeName(objIE.document) = "HTMLDocument" Then
            If InStr(objIE.document.title, "vanguard") > 0 Then
                objIE.Visible = True
                Exit For
            End If
        End If
    Next objIE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM