Created
March 2, 2022 15:38
-
-
Save aev-mambro2/1abb67cd63c3077da54c54cc9203f099 to your computer and use it in GitHub Desktop.
Excel VBA: convert an image link into an actual image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'''''''''''''''''''''''''''''''''''''''''''''''''' | |
'' A sub process to perform the conversion. | |
'' Takes no parameters. | |
'' Has no return value. | |
'' Call it for instance on Workbook_Open(). | |
'''''''''''''''''''''''''''''''''''''''''''''''''' | |
Sub ImageLinksToImages() | |
Dim new_picture_shape As Shape | |
Dim picture_file_name As String | |
Dim picture_width As Long | |
picture_width = 80 'arbitrary | |
Dim picture_height As Long | |
picture_height = 80 'arbitrary | |
Dim picture_left As Long | |
Dim picture_top As Long | |
Dim result As Variant | |
On Error Resume Next | |
For Each s In ThisWorkbook.Sheets | |
Set pictures_input_column = s.Range("L7:L300") 'which column has the images? | |
'Not using a Find, per Microsoft documentation. | |
For Each found In pictures_input_column | |
If Len(found) > 0 And Left(found, 8) = "https://" Then | |
'calculate where to place the new image | |
picture_top = found.Top + WorksheetFunction.Max(0, (found.Height - picture_height)) / 2 | |
picture_left = found.Left + WorksheetFunction.Max(0, (found.Width - picture_width)) / 2 | |
picture_file_name = found 'the cell provides it contents | |
Set new_picture_shape = s.Shapes.AddPicture(picture_file_name, True, True, picture_left, picture_top, picture_width, picture_height) | |
If Not new_picture_shape Is Nothing Then 'just in case the image could not get read | |
found.RowHeight = picture_height | |
new_picture_shape.Placement = xlMoveAndSize | |
new_picture_shape.LockAspectRatio = msoFalse | |
Call found.ClearContents 'avoid duplicate processing | |
End If | |
DoEvents 'allow other processes to work | |
End If | |
Next | |
Next | |
End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A very old tutorial exists on Stack Overflow, for this purpose, with similar code. It doesn't work anymore. The above code is very similar to that. The difference is that the old code accesses a Sheet.Pictures collection, that in the new Excel can't be accessed in the same way. This new code works in Excel 2019.