VB - Excel检查以前的值会产生错误

时间:2013-09-05 14:00:20

标签: excel-vba vba excel

我正在尝试学习一些VB,并且有一个练习来更改一个值并检查之前的值,如果不同则做一些事情。我最终找到了一个我能理解并开始工作的解决方案:How do I get the old value of a changed cell in Excel VBA? - 解决方案4。 我的代码是:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim cell As Variant

    For Each cell In Target
        If previousRange.Exists(cell.Address) Then
            If Not Application.Intersect(Target, Me.Range("B12:B12")) Is Nothing Then
                If previousRange.Item(cell.Address) <> cell.FormulaR1C1 Then
                    cell.Interior.ColorIndex = 36
                End If
            End If
        End If
    Next

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim cell As Variant

    Set previousRange = Nothing 'not really needed but I like to kill off old references
    Set previousRange = CreateObject("Scripting.Dictionary")

    For Each cell In Target.Cells
        previousRange.Add cell.Address, cell.FormulaR1C1
    Next

End Sub

下一个练习是添加一个按钮并根据用户的响应执行操作。所以我补充道:

Private Sub CommandButton2_Click()
    Dim currentValue, message As Integer

    currentValue = Range("C3").Value
    message = MsgBox("Click OK to add 1, cancel to leave", vbOKCancel, "Addition")

    If message = 1 Then
        Range("C3").Value = currentValue + 1
    End If
End Sub

我遇到的问题是该按钮会向C3添加一个,但会在If previousRange.Exists(cell.Address)子句的Worksheet_Change语句中翻转。 所有代码都在Sheet1上定义,但我似乎没有为我的按钮值(C3)生成以前的值。如何生成以前的值,或者我缺少什么?

此致 Ĵ

由于我似乎使事情变得更糟,我创建了一个只包含更改事件代码的新电子表格,而没有其他任何东西可以尝试并简化问题。所以我现在的完整代码是:

Option Explicit
Dim previousRange As New Dictionary

Private Sub Worksheet_Change(ByVal Target As Range)

Dim cell As Variant

For Each cell In Target
    If previousRange.Exists(cell.Address) Then
        If Not Application.Intersect(Target, Me.Range("B12:B12")) Is Nothing Then
            If previousRange.Item(cell.Address) <> cell.FormulaR1C1 Then
                cell.Interior.ColorIndex = 36
            End If
        End If
    End If
Next

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim cell As Variant

Set previousRange = Nothing 'not really needed but I like to kill off old references
Set previousRange = CreateObject("Scripting.Dictionary")

For Each cell In Target.Cells
    previousRange.Add cell.Address, cell.FormulaR1C1
Next

End Sub

现在,如果我更改了B12单元格,则会突出显示previousRange As New Dictionary代码,并显示一条消息“编译错误:用户定义的类型未定义”。 在我介绍消息框并进行后续更改之前,此代码曾经工作过。必须是用户错误。你能帮忙吗?

关心J.

1 个答案:

答案 0 :(得分:0)

.Exists方法用于字典对象,就像你引用的例子一样。但是我没有看到你在代码中声明字典对象的位置。也许你错过了声明声明?

Dim previousrange As New Dictionary

请注意,与您引用的解决方案一样,您需要在子例程之前声明这一点。此外,您还需要启用Microsoft Scripting Runtime。方法如下:

  1. 在VBA编辑器中,转到工具菜单,然后点击引用...
  2. 在“可用引用”列表框中,向下滚动,直至看到 Microsoft Scripting Runtime 。确保选中其复选框。
  3. 点击确定
  4. 现在您可以使用Dictionary对象了。