[英]VBA: How to check IF a specific cell contains an image and then delete the image if it exists
在标题为Counter Party Select
的工作表中,我想检查单元格D2
是否包含想象。 如果单元格确实包含图像(图片),我想删除该图片。 我尝试使用的代码在Set thing = Sheets("Counter Party Select").Range("D2").Select
。
错误消息是Run-time error 4242. Object Required
。 我应该使用什么代码?
Sub Logo_Fill()
Dim myImage As Shape
Dim thing As Object
Set thing = Sheets("Counter Party Select").Range("D2").Select
If TypeName(thing) = "Picture" Then
Set myImage = ActiveSheet.Shapes("Picture 1")
myImage.Delete
End If
End Sub
当你想要单元格 D2 的值时,你应该使用
Dim myImage As Shape
Dim thing As Variant
thing = Sheets("Counter Party Select").Range("D2").Value
deletePictureFromCell
过程的解决方案。deletePictureFromCell
使用它们的地址,而不是您的(有效)解决方案中使用的单元格对象。代码
Option Explicit
Sub Logo_Fill()
Const wsName As String = "Counter Party Select"
Const CellAddress As String = "D2"
Dim wb As Workbook: Set wb = ThisWorkbook ' The workbook with this code.
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim pic As Picture
deletePictureFromCell pic, ws, CellAddress
End Sub
Sub deletePictureFromCell(ByRef PictureObject As Picture, _
Optional Sheet As Worksheet, _
Optional ByVal CellAddress As String = "A1")
If Sheet Is Nothing Then Set Sheet = ActiveSheet
For Each PictureObject In Sheet.Pictures
If PictureObject.TopLeftCell.Address(False, False) _
= Replace(CellAddress, "$", "") Then
PictureObject.Delete
' If only one picture per cell, this could increase efficiency:
'Exit For ' No need to loop anymore.
End If
Next PictureObject
End Sub
With
语句重写代码。.
) .Unprotect
、 .Pictures
和.Range("D2")
。Intersect
前面使用Application
,但最好记住它是Application
object的方法,而不是Workbook
object 的方法。重构
Sub Logo_Fill2()
Dim pic As Picture
With Sheets("Counter Party Select")
.Unprotect
For Each pic In .Pictures
If Not Intersect(pic.TopLeftCell, .Range("D2")) Is Nothing Then
pic.Delete
End If
Next pic
End With
End Sub
我想出了一种使用 for 循环执行此操作的方法:
Sub Logo_Fill()
Dim pic As Picture
Sheets("Counter Party Select").Unprotect
For Each pic In Sheets("Counter Party Select").Pictures
If Not Application.Intersect(pic.TopLeftCell, Range("D2")) Is Nothing Then
pic.Delete
End If
Next pic
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.