[英]How to insert images dynamically based on cell value
I have two column 我有两列
A B
Cat
Lion
Pictures are in c:\\pictures
folder and are in png
format.I have wrote code like this 图片位于
c:\\pictures
文件夹中,并且为png
格式。
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, [A:A]) Is Nothing Then Exit Sub
If Target.Row Mod 20 = 0 Then Exit Sub
On Error GoTo son
ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\" & Target.Value & ".jpg").Select
Selection.Top = Target.Offset(0, 2).Top
Selection.Left = Target.Offset(0, 4).Left
Selection.ShapeRange.LockAspectRatio = msoFalse
Selection.ShapeRange.Height = Target.Offset(0, 2).Height
Selection.ShapeRange.Width = Target.Offset(0, 2).Width
Target.Offset(1, 0).Select
son:
End Sub
The formula works fine. 该公式工作正常。 But when i delete value of A2 or A3 , correspoding picutres did not deleted .
但是当我删除A2或A3的值时,相应的微微像素并没有删除。 And When I again write the item in A2 and A3, Pictures add above old pictures.
当我再次在A2和A3中写入项目时,图片会在旧图片上方添加。
Also is there any way to delete picture if the values of cells A2
and A3
are empty? 如果单元格
A2
和A3
的值为空,还有什么方法可以删除图片?
edited to handle picture absence/presence before adding/deleting it 编辑以处理图片的缺失/存在,然后再添加/删除它
you could name pictures with its parent cell address so that it's easy to reference them once you delete some parent cell content: 您可以使用图片的父单元格地址来命名图片,以便在删除某些父单元格内容后可以轻松引用它们:
Private Sub Worksheet_Change(ByVal target As Range)
If Intersect(target, [A:A]) Is Nothing Then Exit Sub
If target.row Mod 20 = 0 Then Exit Sub
If Not IsEmpty(target) Then '<--| if changed cell content is not empty
If Not IsPicture(target) Then '<--| if there's not a picture whose name matches the target address
With Pictures.Insert("C:\Users\chojwa\Desktop\a\UT\VARIE\software\VBA programming\Forum\Stack Overflow\images" & "\" & target.Value & ".bmp") '<--| insert it
.Top = target.Offset(0, 2).Top
.Left = target.Offset(0, 4).Left
.ShapeRange.LockAspectRatio = msoFalse
.ShapeRange.Height = target.Offset(0, 2).Height
.ShapeRange.Width = target.Offset(0, 2).Width
.name = target.Address '<--| associate the picture to the edited cell via its address
End With
End If
Else '<--| if cell content has been deleted
If IsPicture(target) Then Me.Shapes(target.Address).Delete '<--| delete the picture whose name is associated to the cell via its address, if any
End If
target.Offset(1, 0).Select
son:
End Sub
Function IsPicture(target As Range) As Boolean
On Error Resume Next
IsPicture = Not Shapes(target.Address) Is Nothing
On Error GoTo 0
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.