我有一个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
此代码不起作用,这显示错误"不兼容的类型Err。 13"
关于评论的任何问题。
答案 0 :(得分:2)
我稍微调整了代码(删除了.Select
行)并添加了haveImage
布尔值,以使代码更符合逻辑。我还将Cell
更改为Cel
,因为我发现使用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"))
注意:如果单元格中有不的图片有该图片的左上角,则在单元格中,它将返回" No&#34 ;