Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Range = Range("A1") Then
If Range("A1").Value <> Range("A2").Value Then
Range("C1").Value = Range("C1").Value + 1
Range("A2").Value = Range("A1").Value
End If
End If
End Sub
这就是代码但是当我复制粘贴一个偏移单元格时,比如说 2 列和 3 行
它在线产生运行时错误13类型不匹配
If Target.Range = Range("A1") Then
为什么?
我只是想让 vba 在每次单元格 A1 更改时做一些事情
A1本身的值是一个excel求和公式
最佳答案
您会收到类型不匹配错误,因为您尝试将范围(包含许多单元格)与单个单元格进行比较。如果你想每次都做某事单元格A1
改变了,改用这个:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
On Error GoTo ErrHandler
If Not Intersect(Target, Range("A1")) Is Nothing Then
If Range("A1").Value <> Range("A2").Value Then
Range("C1").Value = Range("C1").Value + 1
Range("A2").Value = Range("A1").Value
End If
End If
ExitHere:
Application.EnableEvents = True
Exit Sub
ErrHandler:
Resume ExitHere
End Sub
另请注意,我正在使用
Application.EnableEvents = False
- 这是Worksheet_Change
的好习惯事件来使用它。每次更改事件处理程序代码中的任何单元格时,它都会阻止代码无限触发自身。更新:
顺便说一句,
the value of A1 itself is an excel sum formula
- 您无法使用上述方法跟踪公式的变化。我在这个问题中详细介绍了如何做到这一点:Using Worksheet_Calculate event for tracking changes of formula
关于vba - excel vba关于单元格更改错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23011606/