在 Excel VBA 中,如果变量是 Excel.Range,并且它引用的范围被删除,则它会丢失其引用。任何访问变量的尝试都会导致Runtime Error 424: object required
.
Dim rng As Range
Set rng = Sheet1Range("A1")
Sheet1.Rows(1).Delete 'Range has been deleted.
Debug.Print rng.Address() 'Any access attempt now raises runtime error 424.
有没有一种方法可以在没有错误处理程序的情况下测试这种“丢失引用”状态?
Testing Nothing
、 Vartype() 和 Typename() 都没有用,因为变量仍然是 Range。我在对象浏览器中逐字阅读了所有 Excel.Application,但什么也没找到。也许有什么我忽略了..?例如 Excel 史前版本中那些奇怪的残留函数之一,例如 ExecuteExcel4Macro()..?
我在谷歌上搜索了这个问题的答案,但没有找到任何有用的东西。
EDIT:
有些人问我为什么要试图避免错误处理程序。这是我的正常编程理念,原因如下:
- 我确实认识到有时错误处理程序是最快的方法,或者是唯一的方法。但这不是最优雅的方式。这对我来说似乎很粗鲁。这就像粉刷栅栏和给我的猫画肖像之间的区别。 =-)
- 我避免使用错误处理程序的另一个原因是教育。很多时候,在寻找替代方案时,我会发现我以前从未了解过的属性、过程、对象,甚至整个库。在这样做的过程中,我找到了更多的盔甲来保护我的代码。
这是一种应该能够解决该问题的方法,尽管它并不是检查它是否已被自行删除的好解决方案。我认为错误处理可能是你最好的方法。
Sub Example()
Dim foo1 As Range
Dim foo2 As Range
Dim foo3 As Range
Dim numberOfCells As Long
Set foo1 = Sheet1.Range("A1")
Set foo2 = foo1.Offset(1, 0) 'Get the next row, ensure this cell exists after row deletion!
Set foo3 = Union(foo1, foo2)
numberOfCells = foo3.Cells.Count
Debug.Print "There are " & numberOfCells & " cells before deletion"
Sheet1.Rows(1).Delete
Debug.Print "There are now " & foo3.Cells.Count & " cells"
If foo3.Cells.Count <> numberOfCells Then
Debug.Print "One of the cells was deleted!"
Else
Debug.Print "All cells still exist"
End If
End Sub
另外,这是一种更加面向功能的方法,这可能是添加到代码库中稍微更好的方法。同样,这并不理想,但它不应该需要错误处理程序。
Private getRange As Range
Sub Example()
Dim foo As Range
Dim cellCount As Long
Set foo = Sheet1.Range("A1")
cellCount = GetCellCountInUnion(foo)
Sheet1.Rows(1).Delete
If Not cellCount = getRange.Cells.Count Then
Debug.Print "The cell was removed!"
Else
Debug.Print "The cell still exists!"
End If
End Sub
Private Function GetCellCountInUnion(MyRange As Range) As Long
Set getRange = Union(MyRange, MyRange.Parent.Range("A50000")) ‘second cell in union is just a cell that should exist
GetCellCountInUnion = getRange.Cells.Count
End Function
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)