什么是自动从Excel / VBA中链接下载图片的方法?

所以这里的情况是:我试图从外部服务器下载一些图片到本地计算机上。

Excel文件有一个链接到图片将打开并下载图片。

到目前为止我所尝试的是将超链接转换为文本(图片url)并运行下面的代码。

我只是基本熟悉VBA,但其他语言更是如此。 这是我到目前为止的代码:

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\My Name\Downloads\" Sub DownloadLinks() 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("B" & Rows.Count).End(xlUp).Row For i = 2 To LastRow '<~~ 2 because row 1 has headers strPath = FolderName & ws.Range("BP" & i).Value & ".jpg" Ret = URLDownloadToFile(0, ws.Range("BP" & i).Value, strPath, 0, 0) If Ret = 0 Then ws.Range("CA" & i).Value = "File successfully downloaded" Else ws.Range("CA" & i).Value = "Unable to download the file" End If Next i End Sub 

列名是不相关的,但现在,所有的东西都是“无法下载文件”,或者如果成功,它不在我指定的目录中。

有没有更好的方法来编码?

关于我的数据的东西也许?

如果可能的话,我也希望将文件名保存为另一列中的文本,但这不是必需的。

现在我只需要他们下载。

尝试这个:

 Sub DownloadLinks() Dim ws As Worksheet Dim LastRow As Long, i As Long Dim strPath As String, strURL As String Dim c As Range Set ws = Sheets("Sheet1") LastRow = ws.Range("B" & Rows.Count).End(xlUp).Row For i = 2 To LastRow Set c = ws.Range("BP" & i) If c.Hyperlinks.Count>0 Then strPath = FolderName & c.Value & ".jpg" strURL = c.Hyperlinks(1).Address Ret = URLDownloadToFile(0, strURL, strPath, 0, 0) ws.Range("CA" & i).Value = IIf(Ret = 0, _ "File successfully downloaded", _ "Unable to download the file") Else ws.Range("CA" & i).Value = "No hyperlink!" End If Next i End Sub