对象删除后仍然存在

Object still exists after deletion

为什么Shape对象删除后还存在?

当我检查形状对象时,它不是什么都没有,因此即使从工作表中可视地删除了形状,它仍然存在。

Sub Delete_shpObj_and_Check_if_Still_Exists()
    Dim ShpObj As Shape
    Set ShpObj = Sheet1.Shapes("Oval 1")

    'check if shape object exists
    If Not ShpObj Is Nothing Then
        MsgBox "Shape Object exists"
    Else
        MsgBox "Shape Object doesn't exist"
    End If

    'Delete the Shape Object
    ShpObj.Delete

    'Test again if shape object exists
    If Not ShpObj Is Nothing Then
        MsgBox "Shape Object exists"
    Else
        MsgBox "Shape Object doesn't exist"
    End If
End Sub

您无法以您的代码尝试的方式检查删除...

正如@horst所说,讨论中的变量仍然赋值给一个对象。即使删除后。

您可以尝试检查对象是否已被删除,将对象重新分配给(相同的)变量,方法如下:

On error resume next
 Set ShpObj = Sheet1.Shapes("Oval 1")
 If Not ShpObj Is Nothing Then    
    MsgBox "Shape Object exists"
    on error GoTo 0
 Else
    err.clear: On Error GoTo 0
    MsgBox "Shape Object doesn't exist, anymore..."
 End If

将您的测试代码包装成一个函数

Public Function ShapeExists(ByVal InWorksheet As Worksheet, ByVal ShapeName As String) As Boolean
    On Error Resume Next
    Dim ShpObj As Shape
    Set ShpObj = InWorksheet.Shapes(ShapeName)
    On Error Goto 0
    ShapeExists = Not ShpObj Is Nothing
End Function

因此您可以像

一样轻松地重复使用它
Sub Delete_shpObj_and_Check_if_Still_Exists()    
    Dim ShpObj As Shape    
    Set ShpObj = Sheet1.Shapes("Oval 1")

    MsgBox ShapeExists(Sheet1, "Oval 1")

    ShpObj.Delete 'delete

    MsgBox ShapeExists(Sheet1, "Oval 1")
End Sub

通过错误处理删除对象

  • 我不是专家,但看起来您需要在删除后立即使用 Set ShpObj = Nothing 或使用 Pᴇʜ 的函数将变量设置两次。
  • 如果您不在第二个确认消息框中写入 Debug.Print ShpObj.Type 之类的内容,或者重复第一个 Set 语句(这将证明它不存在),则会出现错误,但不可接受。

代码

Option Explicit

Sub Delete_shpObj_and_Check_if_Still_Exists()

    Dim ShpObj As Shape
    On Error Resume Next
    Set ShpObj = Sheet1.Shapes("Oval 1")
    On Error GoTo 0
'-----------------------------------------------------
'check if shape object exists
    If Not ShpObj Is Nothing Then
        MsgBox "Shape Object exists"
        Dim msg As Variant
        msg = MsgBox("Shape Object exists. Do you want to delete it?", _
            vbInformation + vbYesNo, "Test Shape Object")
        If msg = vbYes Then
            ShpObj.Delete
            Set ShpObj = Nothing
            Application.ScreenUpdating = True
        End If
    Else
        MsgBox "Shape Object doesn't exist"
    End If
'-----------------------------------------------------
'Test again if shape object exists
    If Not ShpObj Is Nothing Then
        MsgBox "Shape Object exists"
    Else
        MsgBox "Shape Object doesn't exist"
    End If
End Sub