Dears, I have a worksheet where i need to insert 1 or 2 images from a folder on my pc to the Excel file based on cell value
i need to insert image in cell (H43) based on the value in cell (E5) and the other image in cell (L43) baded on the value in cell (G5) and if E5 or G5 is blank to keep the other cell blank and this is my folder source "D:\Desktop\Guards\Guards National IDs" N.B. i have all images also created as hyberlinks on other sheet if this will help (I'm using office 2021)
i have found a code on internet but only can insert one image not two please help me as I'm new to the vba code
thank you dears in advance for help and here is the code i have
Private Sub Worksheet_Change(ByVal Target As Range)
Dim picname As String
Dim pic As Object
Dim source As String
Dim t, l, h, w As Integer
source = Range("H43").Value
picname = "Picture 2"
Set pic = ActiveSheet.Shapes(picname)
With pic
t = .Top
l = .Left
h = .Height
w = .Width
End With
ActiveSheet.Shapes(picname).Delete
Set pic = ActiveSheet.Shapes.AddPicture(source, False, True, l, t, w, h)
pic.Name = picname
End Sub
please modify the code to insert 2 images not one
By
I'm assuming you mean if E5 is cleared then make sure Picture 1 doesn't exist and if G5 is cleared then make sure Picture 2 doesn't exist (though a commented out line is included to use if you also want to clear the path values in H43 and L43). [Edit: I just noticed I'm mentioning blank shapes in the text in cells H43 and L43 - I considered then decided against using blanks as placeholders, but forgot to remove the extra text from the cells in the screenprints below; the text should have been something like: 'The path to picture 1 is stored in H43' and 'The path to picture 2 is stored in L43'.]
Let's say we're starting off with the following inside the worksheet:
Then changing E5 to a non-blank value adds Picture 1 based on the path in H43:
Changing G5 to a non-blank value also adds Picture 2 based on the path in L43:
Similarly, changing the values to blanks, removes the respective:
The code prints out the following for the four steps above:
Here's the code:
Here's the code with the hardcoded path per your comments below (remember to change picture1.png and picture2.png file names in the array called 'a' if your file names are different):
Here are the additional updates to the code per your comments below:
Here's the update per your latest comment (numbers in E5,G5 correlate to picture file names - the code searches the folder from the path String for a file containing the corresponding number in it's name):
Code:
Added dynamic resizing of picture shapes if the destination cells are merged. Also added base file name to more accurately/consistently match conditions to picture names:
Add date to D11 per your other question: