vba - 使用 Excel VBA 从当前 Internet Explorer 浏览器 session 下载 PDF?

标签 vba excel internet-explorer pdf download

我希望自动从公司网站下载多个 PDF。此站点仅适用于我们的内部公司网络/VPN,并且需要身份验证(并且也仅限 https)。

我研究过通过 VBA/python 登录,但遇到了麻烦。我想是由于我们的公司网络设置和访问该站点的限制的某种组合。

我认为最简单的方法是只使用现有的浏览器 session 来下载文件,而不用担心所有身份验证和网络问题?

我改编了我在网上找到的 VBA 代码,以识别一个变量并将其设置到一个现有的、经过身份验证的 IE 窗口,并导航到我们公司网站上的 PDF(见下文)。

如何从那里自动保存现有浏览器 session 中的 PDF 页面?我在网上看到的几种在 IE 中保存文件的方法似乎不起作用。如果这通过 python 更容易,我也对此持开放态度。 谢谢!

marker = 0
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
    On Error Resume Next    ' sometimes more web pages are counted than are open
    my_url = objShell.Windows(x).Document.Location
    my_title = objShell.Windows(x).Document.Title

    If my_title Like "XYZ" & "*" Then 'compare to find if the desired web page is already open
        Set ie = objShell.Windows(x)
        marker = 1
        Exit For
    Else
    End If
Next

If marker = 0 then
    msgbox("A matching webpage was NOT found")
Else
    msgbox("A matching webpage was found")
    ie.navigate("https://corpwebsite.com/abcdef.pdf")
End If

最佳答案

尝试 URLMon 直接从 URL 下载?假设您已处理任何身份验证问题。

Option Explicit

#If VBA7 And Win64 Then
    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 Long

#Else
    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

Public Const BINDF_GETNEWESTVERSION As Long = &H10
Public Const folderName As String = "C:\Users\User\Desktop\abcdef.pdf" '<=Change as required

Public Sub downloadPDF()
    'Authentication code first. Maybe in a different sub.
    Dim ret As Long
    ret = URLDownloadToFile(0, "https://corpwebsite.com/abcdef.pdf", folderName, BINDF_GETNEWESTVERSION, 0)
End Sub

关于vba - 使用 Excel VBA 从当前 Internet Explorer 浏览器 session 下载 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51234543/

相关文章:

javascript - 在 IE 中隐藏选项标签

html - 从表格中抓取 Excel VBA Web

vba - 我的代码生成一个无限循环

Excel VBA : Passing a range name as a function argument

jquery - jQuery选择器在Windows Phone 7上不起作用

css - DIV 颜色在 IE 中无法正确显示

vba - MS Access 2016 TreeView 错误 : "No object in this control element. Runtime error 438"

java - 如何在apache POI中自动调整excel中的列

excel - SUMIFS excel 公式中省略空格

excel - 使用自定义元动态定价规则导入 WooCommerce 产品