Excel VBA: Insert Picture from Directory on Cell Value Change Without Error

Опубликовано: 07 Октябрь 2024
на канале: Anant Services
2,977
32

Insert a picture from the directory on the change of a cell value using Excel VBA.

In this video tutorial when someone changes the value of cell B2, a picture is automatically inserted from a folder in the directory. The cell is also automatically resized to be the same as the picture.

CODE Link : https://personalcomputer85.blogspot.c...


This macro can be placed in a sub procedure and does not need to run on the worksheet change event. It could also be used in a loop to insert multiple pictures from that directory.

Below is the code used in the video. This can be copied and adapted for your own needs.

CODE :

Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False

Dim myPict As Picture
Dim PictureLoc As String

If Target.Address = Range("b3").Address Then

ActiveSheet.Pictures.Delete

PictureLoc = "D:\\FLIPKART\flipkartp\" & Range("b3").Text & ".jpg"

With Range("g3")
On Error GoTo errormessage:
Set myPict = ActiveSheet.Pictures.Insert(PictureLoc)

myPict.Height = 300
myPict.Width = 200
myPict.Top = .Top
myPict.Left = .Left
myPict.Placement = xlMoveAndSize
myPict.ShapeRange.LockAspectRatio = msoTrue

errormessage:
If Err.Number = 1004 Then

MsgBox "File does not Exist, Please first update photo with .jpg File"

End If
End With
End If
Application.ScreenUpdating = True
End Sub