【问题标题】:VBA: download file without extension, get extension and add it to filenameVBA:下载没有扩展名的文件,获取扩展名并将其添加到文件名
【发布时间】:2016-09-06 17:57:57
【问题描述】:

此 VBA 脚本使用 A 列作为文件名,B 列作为图像 url,并添加“.jpg”作为扩展名。

问题是许多文件不是​​ jpg 格式,因此最好将它们视为具有未知扩展名。

是否可以调整脚本,使其在保存图像之前获得真实的文件扩展名,并将其添加到文件名而不是用户定义的“.jpg”?

脚本

Option Explicit
'~~> This macro downloads images from urls. Column A=image title, Column B=image URL.
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\plus\Desktop\INPUT\"

Sub DOWNLOAD_image_XLS()
'~~> This is where text is divided into 2 columns right down the "|" delimiter
    Columns("A:A").Select
    Selection.TextToColumns Destination:=Range("A1") _
                      , DataType:=xlDelimited _
                      , Other:=True _
                      , OtherChar:="|"
    Dim ws As Worksheet
    Dim LastRow As Long, i As Long
    Dim strPath As String

    Set ws = ActiveSheet

    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 = "OK"
        Else
            ws.Range("C" & i).Value = "Failed!"
        End If
    Next i
    End Sub

【问题讨论】:

  • 在哪里可以找到“真实文件扩展名”?它是链接的一部分吗?然后您可以使用splitmid 以及InStrRev 从那里轻松提取它。还是您想编写代码来检查文件并查找标识文件的可能标头?
  • @Ralph 没有指定真正的扩展名,这是问题所在,大多数文件是 jpg,很多是 png 和一些 gif。理想的解决方案是您提到的后者,让脚本检查文件并获取其扩展名。这在 VBA 中可行吗?
  • in this post 所述,使用现有库执行此操作会容易得多。然而,您当然也可以仅使用 VBA 来实现这一点。但是如果你想走这条路,那么你必须先自己编写代码(虽然我们可以帮助你调试它)或者花钱请人为你做这件事。或者,只需获得一个新的图片查看程序,它会为您执行此操作(识别图片,无论其扩展名如何)。
  • 对于使用 VBA 的 Excel 中的 .net 实现(如上述引用问题的答案之一中所建议),您可能需要查看以下内容:codeproject.com/Articles/555660/…

标签: excel vba


【解决方案1】:

一种方法是从响应中解析Content-Type

Sub DownloadLink()

  Const imageLink = "http://i.stack.imgur.com/9w2PY.png?s=32"
  Const filePath = "C:\Temp\myimage"

  Dim req As Object, content() As Byte, extension$

  ' send the request
  Set req = CreateObject("Msxml2.ServerXMLHTTP.6.0")
  req.Open "GET", imageLink, False
  req.Send

  ' get the extension and data
  extension = "." & Split(req.getResponseHeader("Content-Type"), "/")(1)
  content = req.responseBody

  ' write the file
  Open filePath & extension For Binary Access Write As #1
      Put #1, 1, content
  Close #1

End Sub

【讨论】:

  • 天才!它得到正确的扩展名。我会尽力将 2 个脚本“合并”在一起,并让您从我的 csv 文件中获取图像链接。谢了!
  • 嗯,我不会编码,甚至无法阅读 =D。我最终下载了图像并在没有扩展名的情况下保存它们,然后使用 TrID 批处理添加文件扩展名。两步而不是一步,但它可以完成这项工作。
猜你喜欢
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
  • 1970-01-01
  • 2019-01-26
  • 2016-12-24
  • 2015-02-14
  • 1970-01-01
相关资源
最近更新 更多