我有这个sub应该在更改相应的单元格时更新单元格的值,但是我不断收到错误,指出错误13类型不匹配,我查找了这个问题的所有可能来源并且无法弄清楚是什么导致它,这是我的代码提出问题:
Private Sub Worksheet_Change(ByVal Target As range)
'Adds unique keyA values
'Check to see if the changed cell is in column H
If Not Intersect(Target, range("H:H")) Is Nothing Then
If Target.Cells.Value <> "" And Target.Row > 7 And Target.Row <= 20 Then
'Update the "KeyA" value
range("A" & Target.Row).Value = Now()
End If
End If
'Adds unique keyB values
'Check to see if the changed cell is in column J
If Not Intersect(Target, range("J:J")) Is Nothing Then
If Target.Cells.Value <> "" And (Target.Row > "7" And Target.Row <= "27") Then
'Update the "KeyB" value
range("M" & Target.Row).Value = Now()
End If
End If
End Sub
当我尝试清除其检查更改的范围时,会发生错误。任何帮助解决这个问题都将非常感谢,谢谢!
答案 0 :(得分:2)
您忘记了Target
是一个范围,并不一定只包含一个单元格。如果您稍微调整一下代码,它应该可以工作:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim cell As Range
'Adds unique keyA values
'Check to see if the changed cell is in column H
If Not Intersect(Target, Range("H:H")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And Target.Row > 7 And Target.Row <= 20 Then
'Update the "KeyA" value
Range("A" & Target.Row).Value = Now()
End If
Next cell
End If
'Adds unique keyB values
'Check to see if the changed cell is in column J
If Not Intersect(Target, Range("J:J")) Is Nothing Then
For Each cell In Target.Cells
If cell.Value <> vbNullString And (Target.Row > "7" And Target.Row <= "27") Then
'Update the "KeyB" value
Range("M" & Target.Row).Value = Now()
End If
Next cell
End If
End Sub
基本上,更改是它现在检查范围Target
中的每个单元格,并为该范围内的每个单元格运行代码。之前,您正在比较(可能)多个Target.Values
到""
。那不行。现在,只有一个.Value
与""
进行比较,这应该可以解决它。