如何通过身份验证从URL下载图像

时间:2014-08-11 07:40:43

标签: vba excel-vba excel

我有一个代码,通过该代码我可以从非身份验证网站URL下载图像。它适用于那些网站,但当我尝试通过网址下载图像,网站像Dropbox。它给了我一个错误。

现在我想要的是这个,我想要一个代码,我可以通过该代码从经过身份验证和未经过身份验证的网站网址下载图片。

以下是我的代码:

Option Explicit

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

Dim Ret As Long

'~~> This is where the images will be saved. Change as applicable
Const FolderName As String = "C:\Users\INTEL\Desktop\Hari\Images\"

Sub Sample()
    Dim ws As Worksheet
    Dim LastRow As Long, i As Long
    Dim strPath As String

    '~~> Name of the sheet which has the list
    Set ws = Sheets("Sheet1")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

    For i = 2 To LastRow '<~~ 2 because row 1 has headers
        strPath = FolderName & ws.Range("A" & i).Value & ".jpg"

        Ret = URLDownloadToFile(0, ws.Range("B" & i).Value, strPath, 0, 0)

        If Ret = 0 Then
            ws.Range("C" & i).Value = "File successfully downloaded"
        Else
            ws.Range("C" & i).Value = "Unable to download the file"
        End If
    Next i
End Sub

1 个答案:

答案 0 :(得分:1)

如果您的网址以蓝色突出显示,请点击第一个网址。 Excel应该打开一个窗口,您可以在其中验证连接。输入服务器的用户名和密码,然后勾选下面的复选框以保存凭据。

如果您的网址没有突出显示,请使用= url(a1)在其旁边添加列,然后点击它。

一旦excel记住您的凭据,您就可以执行您的脚本。