I am having difficulty figuring out how to add an image from a link into a VBA image control.
I can bring the image into VBA with the following:
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.
You can use the standard windows dll urlmon
for this, and you should declare it's URLDownloadToFile
function on top of your module.
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.
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. If you plan to download GIF or PNG you'll have to adapt the tempfile extension accordingly.
This MrExcel.com thread has the answer you're looking for. Basically there is a way of assigning a picture to an image control at runtime by using the "LoadPicture(file path)" method. Unfortunately for you it does not take URLs as the file path. If the picture were in a Local or Shared Drive "LoadPicture" would be the way to go. Sorry...
LoadPicture() method example:
'Having that "Image1" is the name of the Image Control
Image1.Picture = LoadPicture("here the path to your picture")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.