Excel VBA Range对象被设置,但内部对象丢失

我有一个令人困惑的问题与我的VBA范围对象。 这里是第一个相关的代码

Option Explicit Dim lastSelection As Range ' <= Always remember last Selection Private Function UpdateNeeded() As Boolean UpdateNeeded = False If IsEmpty(lastSelection) Then Debug.Print "UpdateReason: lastSelection=<Empty>" UpdateNeeded = True ElseIf lastSelection Is Nothing Then Debug.Print "UpdateReason: lastSelection=<Nothing>" UpdateNeeded = True ' Next line causes an "Object-Missing" exception ElseIf Selection.Count <> lastSelection.Count Then Debug.Print "UpdateReason: Selection.Count <> lastSelection.Count" UpdateNeeded = True ' ElseIf (A lot of other if statements always to be handled the same way ...) End If End Function Private Sub Worksheet_Change(ByVal Target As Range) If UpdateNeeded Then Set lastSelection = Selection 'UpdateAllCharts ' Update all my containing charts into worksheet. End If End Sub 

这是工作正常,直到我开始删除单元时,他们holded在lastSelection。 然后它会导致“对象缺失”exception。 debugging对象如下所示:

 | Expression | Value | Type | Context +-----------------+-------------------+-------------+------------------------ | lastSelection | | Range/Range | Sheet1.Worksheet_Change | |- ... | "Object Required" | ... | Sheet1.Worksheet_Change | |- Cells | "Object Required" | Range | Sheet1.Worksheet_Change | |- Count | "Object Required" | Long | Sheet1.Worksheet_Change | |- ... | "Object Required" | ... | Sheet1.Worksheet_Change 

我知道发生了什么事,但是我不知道如何处理。 IsEmpty,没什么,IsMissing不会改变任何东西。 唯一的方法似乎设置OnError,但在某些情况下,可能会导致相反的方式,所以我不能自动更新我的图表。

我GOOGLE了很多,但我无法find任何解决scheme。 有人能帮我吗?

顺便说一下,我怎么能在这里实现表格? HTML似乎没有工作。

Thx提前

我不确定你想用Selection.Count <> lastSelection.Count语句来捕获什么版本问题,所以我的代码可能需要一些改变才能在你的情况下工作,但是我认为如果你直接使用预定义的Targetvariables而不是定义一个Module scoped Rangevariables,它会让你解决Object-Missingexception。

这是我在想什么的例子。 当一个单元格或行被删除时,此代码不会收到Object-missingexception:

 Option Explicit Dim lastSelection As Long '~> Always remember the count of last Target Private Function UpdateNeeded(ByVal Target As Range) As Boolean '~>Pass target and 'use that range UpdateNeeded = False If IsEmpty(Target) Then '~> Passed argument instead of module variable Debug.Print "UpdateReason: lastSelection=<Empty>" UpdateNeeded = True ElseIf Target Is Nothing Then '~> Passed argument instead of module variable Debug.Print "UpdateReason: lastSelection=<Nothing>" UpdateNeeded = True '~>"Object-Missing" exception no longer occurs on deletion, but does this still 'do what you want? ElseIf Target.Count <> lastSelection Then Debug.Print "UpdateReason: Selection.Count <> lastSelection.Count" UpdateNeeded = True End If End Function Private Sub Worksheet_Change(ByVal Target As Range) If UpdateNeeded(Target) Then lastSelection = Target.Count '~> tracking against Target.Count could eliminate 'the reference issue. 'UpdateAllCharts End If End Sub