2013-09-05 29 views
0

我想学习一点VB,并有一个练习来改变一个值,并检查以前的值,如果它是不同的做一些事情。我终于找到了一个解决方案,我能理解,并获得来自工作:How do I get the old value of a changed cell in Excel VBA? - 液4. 我的代码是:VB - Excel检查以前的值给出了一个错误

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,但随后在对Worksheet_Change子的If previousRange.Exists(cell.Address)声明翻倒。 所有代码都是在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.

回答

0

的.Exists方法用于在字典对象,例如您所列举的例子。但是我没有看到你在代码中声明了哪个字典对象。也许你错过了它的声明声明?

Dim previousrange As New Dictionary 

请注意,就像您引用的解决方案一样,您需要在子例程之前声明它。另外,您需要启用Microsoft脚本运行时。具体方法如下:

  1. 在VBA编辑器,进入工具菜单,点击引用...
  2. 在可用引用列表框中,向下滚动,直到您看到Microsoft脚本运行时 。确保它的复选框被选中。
  3. Click OK

现在您可以使用Dictionary对象。

+0

亚伦,我想我已经倒退了。我试着添加你的代码,但我仍然有错误。只要incase我错了我删除了我添加了(这是不承认和包括一个评论),并再次尝试。我现在正在'未定义用户定义类型'。我担心我删除了通用目录类,我不知道如何将其添加回来? J – user2750980

+0

嗯,不知道发生了什么事。也许你可以添加你现有的东西,到你最初的问题的结尾?你可以通过编辑你的问题来做到这一点。 –

+0

亚伦,我编辑了我的问题。在此先感谢J. – user2750980