【发布时间】:2016-05-01 16:29:12
【问题描述】:
编辑: 我发现这段代码可以从 xls 文件中下载图像。 来源:GET pictures from a url and then rename the picture
代码:
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:\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("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
它适用于 xls 文件,其中“PIC NAME”和“URL”位于两个单独的列中。我有一个 csv 文件,与 xls 不同,csv 的值在一列中,由“|”分隔(图片名称|网址)。所以 - 作为编码的菜鸟 - 作为一种解决方法,我在 Excel 中使用“文本到列”将行分成分隔符“|”下方的 2 个单独的列,这样我就可以使用原始代码。
问题:有没有办法让代码与 csv 文件一起使用?这样可以更快、更轻松地从包含数千行的大型 csv 文件中提取图像。
【问题讨论】:
-
请删除绒毛 - 问题中不包含问候语,这是一个问答网站,而不是论坛。此外,请描述您尝试过的方法以及您的问题所在。目前,这个问题不是关于任何编程问题,而是一个“请为我编写整个代码”,这不是这个网站的目的。
-
实际上来自该站点stackoverflow.com/questions/15641717/… 的建议显示了如何做到这一点。
-
您能告诉我们到目前为止您的研究成果吗?谷歌搜索“vba 下载文件”将我带到stackoverflow.com/questions/17877389/…。你试过吗?同样,搜索“vba looplines in file”会产生很多有用的(堆栈溢出)解决方案来读取文件的内容。如果您仍然对此有疑问,您应该重新表述您的问题,以更具体地说明究竟什么不适合您。
-
@Leviathan 是的,我已经更新了 OP,详细说明了我如何解决这个问题。事实上,我已经找到了解决方法。如果有办法调整原始代码以使其与 csv 文件一起使用,那就太好了。
标签: excel image vba csv download