我可以使用 VBA 将 Web 中的图像 (gif) 导入 Excel 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8993154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use VBA to import images (gifs) from the web into Excel?
提问by Excellll
I have a list of URLs to .gif files in an Excel sheet. I want to use VBA to query these websites and insert these images into the same worksheet. I am using Excel 2007.
我在 Excel 工作表中有一个指向 .gif 文件的 URL 列表。我想使用 VBA 查询这些网站并将这些图像插入到同一个工作表中。我正在使用 Excel 2007。
I tried using the 'Get External Data - From Web' feature to query the website, but it returned the following error:
我尝试使用“获取外部数据 - 从 Web”功能来查询网站,但它返回以下错误:
"Unable to open http://.../blah.GIF. The Internet site cannot return the object you request. (HTTP/1.0 403)"
“无法打开http://.../blah.GIF。Internet站点无法返回您请求的对象。(HTTP/1.0 403)”
Is this because Excel cannot import online images with this feature? Or is this problem specifically related to the website?
这是因为 Excel 无法使用此功能导入在线图像吗?或者这个问题是否与网站特别相关?
And most importantly, is there some other way to do this entirely in VBA?
最重要的是,有没有其他方法可以完全在 VBA 中做到这一点?
回答by mischab1
Yes, you can do so. It is actually quite easy. Excel has a AddPicture function. From Excel VBA Help:
是的,你可以这样做。这实际上很容易。Excel 有一个 AddPicture 函数。从 Excel VBA 帮助:
expression.AddPicture(Filename, LinkToFile, SaveWithDocument, Left, Top, Width, Height)
表达。添加图片(文件名、链接到文件、SaveWithDocument、左侧、顶部、宽度、高度)
Use like this:
像这样使用:
Sheets(1).Shapes.AddPicture "http://www.mywebsite.com/images/map.gif" _
, msoFalse, msoTrue, 100, 100, 500, 600
Left, Top, Width, & Height are all required and in points.
Left、Top、Width 和 Height 都是必需的,以磅为单位。
回答by JimmyPena
First you'll want to download the image. There are several methods for doing this. I use the URLDownloadToFile API.
首先,您需要下载图像。有几种方法可以做到这一点。我使用 URLDownloadToFile API。
Use the URLDownloadToFile API function to download a file from a URL into a file*:
使用 URLDownloadToFile API 函数将文件从 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
(*visit link for full code)
(*完整代码请访问链接)
Then a code sample like this will import them onto the worksheet wherever you like:
然后像这样的代码示例会将它们导入到您喜欢的工作表中:
From Insert pictures using VBA in Microsoft Excel*:
从在 Microsoft Excel 中使用 VBA 插入图片*:
Sub TestInsertPicture()
InsertPicture "C:\FolderName\PictureFileName.gif", _
Range("D10"), True, True
End Sub
(*visit link for full code)
(*完整代码请访问链接)
To be fair to the original authors, I won't repost the code in its entirety here. Apologies for a mostly link-based answer.
为了对原作者公平,我不会在这里完整地重新发布代码。为主要基于链接的答案道歉。