Hi Forum members,
A bit another kind of question I came across.
When you have a hyperlink to a picture of something, how to add the picture easily in the Excel file?
You can do this of course by hand: clicking on the link, copy the picture from the internet and paste it in the right cell you want it.
But that's a lot of work with, let's say hundreds of picture-links and that is what we are talking about.
I have an example in the attachment.
Thanks for suggestions or solutions!
Frans
You can use a simple loop:
Sub loadPictures()
For Each cell In Selection
addpic cell.Value, cell.Offset(, -1)
Next cell
End Sub
Sub addpic(url As String, ToRange As Range)
ActiveSheet.Shapes.AddPicture Filename:=url, linktofile:=False, savewithdocument:=True, Left:=ToRange.Left, Top:=ToRange.Top, Width:=60, Height:=60
End Sub
If you want to maintain the original height and width, use -1 rather than 60, but your sample image is quite large!
Thanks very much Velouria!
I don't know much about VBA, although I started several times with some courses.
Somehow or somewhere we don't match VBA and I 🙂
So: Is this the 'complete' code that'll work, or do I have to fill in some range or cells or anything so it 'knows' what to do? And how to start it up?
The sample picture when imported is indeed very big, that's why I adjusted it to something smaller. The person who asked me thinks this is the right size.
Frans
All you need to do is select the cells containing the URLs and then run the loadPictures macro (note: I assumed that all the selected cells will have valid URLs in them).
Thanks again Velouria! I will test it in some days and let you know.
Frans
The original code didn't work for me.
After a little modification it looks OK.
Sub loadPictures()
For Each cell In Selection
Call addpic(cell.Value, cell.Offset(, 1))
Next cell
End Sub
Sub addpic(url As String, ToRange As Range)
ActiveSheet.Shapes.AddPicture Filename:=url, linktofile:=False, savewithdocument:=True, Left:=ToRange.Left, Top:=ToRange.Top, Width:=60, Height:=60
End Sub
Sunny
Hi Sunny,
In what way did it not work? (Adding Call is never necessary in VBA)
Hi Velouria
My bad.
Agreed, call is never necessary in VBA.
The issue is the offset(,-1). It gives Run-time error '1004'. Application-defined or object-defined error
This is due to me testing with the URLs in column A and expecting the pictures/images to be inserted to the right in column B, unlike Fran's request to be inserted to the left of the URLs.
So I changed it to 1 (right) instead of -1 (left). Sorry for the confusion.
Thanks for the codes.
Sunny
Thanks for letting me know.
Hi Velouria, Sunny,
Just a message to let you know everything is working fine here as well! I tested it with an extract of the given data and that's perfect.
I now have to do it with some more columns and rows, but I expect no problems.
Thanks very much also on behalve of the person who asked me this question.
Frans