简体   繁体   English

从Internet添加图像到VBA图像控件

[英]Adding Images from Internet into VBA Image Control

I am having difficulty figuring out how to add an image from a link into a VBA image control. 我很难弄清楚如何将链接中的图像添加到VBA图像控件中。

I can bring the image into VBA with the following: 我可以使用以下内容将图像带入VBA:

Sheets("Elk").Shapes.AddPicture "http://images.summitpost.org/original/562016.jpg", msoFalse, msoTrue, 200, 200, 800, 700

This populates the picture onto the worksheet, but now I want to be able to place it into an image control. 这会将图片填充到工作表中,但现在我希望能够将其放入图像控件中。

Is this a feasible task? 这是一项可行的任务吗?

You can't add an URL to the ActiveX Image Control (I suppose this is the one you're using), you have to save the image on your HDD first. 您无法将URL添加到ActiveX Image Control(我想这是您正在使用的URL),您必须先将图像保存在HDD上。

You can use the standard windows dll urlmon for this, and you should declare it's URLDownloadToFile function on top of your module. 您可以使用标准的Windows动态链接库urlmon对于这一点,你应该把它声明的URLDownloadToFile您模块顶部功能。

Choose a temporary folder on any of your HDD to download the image, then assign it to your Image Control, and finally delete the file. 选择任何HDD上的临时文件夹以下载图像,然后将其分配给图像控件,最后删除该文件。

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



Private Sub Testit()
    Image_Download "http://images.summitpost.org/original/562016.jpg"
End Sub 

Private Sub Image_Download(strImgURL As String)  

        Dim lngRC As Long

        strTempFile = "C:\temp\anyfilename.jpg"

        lngRC = URLDownloadToFile(0, strImgURL, strTempFile, 0, 0)

        If ret Then
            MsgBox "The image download failed", vbExclamation

        Else

          MyImageControl.Picture = LoadPicture(strTempFile)
          Kill strTempFile  

        End If

End Sub

Pay attention to the image format. 注意图像格式。 This will work only if you keep on JPG. 这只有在你继续使用JPG时才有效。 If you plan to download GIF or PNG you'll have to adapt the tempfile extension accordingly. 如果您打算下载GIF或PNG,则必须相应地调整tempfile扩展名。

This MrExcel.com thread has the answer you're looking for. 这个MrExcel.com 主题提供了您正在寻找的答案。 Basically there is a way of assigning a picture to an image control at runtime by using the "LoadPicture(file path)" method. 基本上有一种方法是通过使用“LoadPicture(文件路径)”方法在运行时将图像分配给图像控件。 Unfortunately for you it does not take URLs as the file path. 不幸的是,它不会将URL作为文件路径。 If the picture were in a Local or Shared Drive "LoadPicture" would be the way to go. 如果图片在本地或共享驱动器中“LoadPicture”将是要走的路。 Sorry... 抱歉...

LoadPicture() method example: LoadPicture()方法示例:

'Having that "Image1" is the name of the Image Control
Image1.Picture = LoadPicture("here the path to your picture")  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM