【问题标题】:Download pictures from hyperlink to specific folder从超链接下载图片到特定文件夹
【发布时间】:2017-02-19 10:46:22
【问题描述】:

我有一个 excel 文件,其中包含文件夹名称 (col A)、图片名称 (col B) 和超链接 (col C) p>

文件夹名称图片名称网址

文件夹 1 图像 1 超链接 1

文件夹2图片2超链接2

文件夹 3 图像 3 超链接 3

我找到了这段代码:

Option Explicit

Private Declare PtrSafe 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:\TEMP\"

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("B" & i).Value & ".jpg"

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

    If Len(Dir(FolderName, vbDirectory)) = 0 Then
        MkDir FolderName
    End If

    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

它将文件下载到 C:\TMP\ 但我希望它连续下载每个文件到相应的文件夹 (col A)

【问题讨论】:

  • 一行中只有一个超链接/文件/文件夹?
  • 是的,一个文件,一个文件夹。它应该是连续 4 个超链接,但一个也可以做到这一点。

标签: vba excel hyperlink


【解决方案1】:

这很简单。

由于您使用 CONSTANT 作为保存目录Const FolderName As String = "c:\TEMP\",如果您将代码复制粘贴到您的工作簿中,您不会走得太远。

您应该首先尝试了解代码的工作原理并尝试一下,但无论如何......

如果不插入Const 行,您必须Dim 一个变量,该变量将包含您的目录字符串,并且每次更改行时都会更改。基本上在这里:

For i = 2 To LastRow

    FolderName = ws.Range("A" & i).text ' this is how you get the folder name from column "A" every line
    strPath = FolderName & ws.Range("B" & i).Value & ".jpg"

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

    If Len(Dir(FolderName, vbDirectory)) = 0 Then
        MkDir FolderName
    End If

    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

【讨论】:

  • 非常感谢您的回复。我注意到代码中的 Constatn 文件夹,但我不想自己玩这个。显然它创建了文件夹,但图片没有保存在文件夹中。我得到具有正确名称和图片的文件夹,例如“文件夹 1 图像 1”。所以基本上我希望它使用来自 col B 的名称和来自 col A 的文件夹保存文件。
  • 您是否收到“文件已成功下载”或“无法下载文件”?
  • 您能否检查一下文件是否下载到 c:\TEMP 中?
  • 正在创建文件夹,正在下载文件,但在文件夹之外。两者都在:c:\USERS\user\Documents
  • 我收到“文件已成功下载”或“无法下载文件”。
猜你喜欢
  • 2018-06-26
  • 1970-01-01
  • 2023-03-03
  • 2020-03-08
  • 1970-01-01
  • 2012-08-27
  • 2010-09-05
  • 2013-06-05
  • 2015-09-19
相关资源
最近更新 更多