exceltypes不匹配错误在私人子

我有这个应该更新单元格的值,当一个相应的单元格更改,但我不断收到一个错误,说错误13types不匹配,ive查找所有可能的来源,这个问题,并找不出是什么原因造成的,这是我的代码呈现的问题:

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 

当我尝试清除它的检查范围时发生错误。 任何帮助搞清楚这将不胜感激,谢谢!

你忘了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被比较为"" ,这应该解决它。