在Excel列VBA中插入图像
我有一个VBA代码,无论我input图像名称,它都会在右侧单元格的Excel工作表中插入图像。 但我希望它只能在A:B范围内工作:在列A的单元格中键入名称,它将在下一个单元格B列中插入图像。下面是我想要修改的代码:
Private Sub Worksheet_Change(ByVal Target As Range) Dim c As Range Dim myPath As String myPath = "P:\" Application.ScreenUpdating = False For Each c In Target.Cells If Not Dir(myPath & "*" & c.Text & "*") = "" Then InsertPicture myPath & Dir(myPath & "*" & c.Text & "*"), c.offset(0, 1) End If Next c Application.ScreenUpdating = True End Sub ' Sub InsertPicture(thePath As String, theRange As Range) With ThisWorkbook.ActiveSheet.Pictures.Insert(thePath) With .ShapeRange .LockAspectRatio = msoTrue .Width = theRange.Width .Height = theRange.Height End With .Left = theRange.Left .Top = theRange.Top .Placement = 1 .PrintObject = True End With End Sub
先谢谢你!
你只需要检查Target.Address
( Target
是修改的范围)。 我也要计算Target
,确保它只有一个Range
:
If (Target.Count > 1) Or (Split(Target.Address,"$")(1) <> "A") Then Exit Sub
说明:上面的testing应该在动作macrosWorksheet_Change
的开始处完成,并执行以下操作:
-
Target.Count
返回Target
的单元格数量(Target.Count
更改的单元格数量)。 因为我猜你希望用户一次只input一个图像的名字,你检查Target.Count
,如果它大于1你Exit Sub
- 第二个检查是在列字母上。 variables
Target.Address
返回这样的地址(例如):$A$15
。 你用分隔符$
Split
这个string,所以函数Split(Target.Address,"$")
将会返回一个这样的数组:(("","A","15")
。 你得到它的第二个元素(1)
,然后用值“A”来testing它。 如果不是"A"
(即,如果用户修改了不在列A
的单元格),则Exit Sub
并且不附加任何图像。