检查Excel VBA中是否存在单元格范围内的图像
我有一个Excel文件,我想检查是否存在一个单元格范围内的图像。
我一直在尝试使用下面的代码:
Sub findImage(Cell As Range) Dim Caddress As String Dim Pict As Excel.Picture Application.Volatile Sheets("Sheet1").Select Caddress = Cell.Address 'Assign the range For Each Pict In ActiveSheet.Pictures 'Check for each picture in the range If Pict.TopLeftCell.Address = Caddress Then 'if exists in the range shows a message MsgBox "The image exists!" Exit For 'break for Exit Sub 'break sub End If Next Pict MsgBox "NO", vbInformation 'if not exists shows a message End Sub
此代码不起作用,这显示错误“不兼容types错误13”。
任何问题发表评论。
我调整了一些代码(删除了.Select
行)并添加了haveImage
布尔值,使代码更加合乎逻辑。 我也改变了Cell
,因为我发现使用Cell
可能会与Cells
混淆。
Sub findImage(Cel As Range) Dim Caddress As String Dim shp As Shape Dim haveImage As Boolean haveImage = False Application.Volatile ' Sheets("Sheet1").Activate Caddress = Cel.Address 'Assign the range For Each shp In Sheets("Sheet1").Shapes 'Check for each picture in the range If shp.Type = msoPicture Then If shp.TopLeftCell.Address = Caddress Then 'if exists in the range shows a message haveImage = True Exit Sub 'break sub End If End If Next shp If haveImage Then Exit Sub Else MsgBox "NO", vbInformation 'if not exists shows a message End If End Sub
要使用它,你可以这样调用它: Call findimage(Sheets("Sheet1").Range("C12"))
注意:如果单元格的图片没有该图片的左上angular,则在单元格中将返回“否”。