我的工作簿中有以下两个模块:
Private Sub Worksheet_Change(ByVal Target As Range)
' check if target is in Column B or Column G
If Target.Column = 2 Or Target.Column = 7 Then
Select Case Target.Row
Case 12 To 18, 26 To 32 'check if target row is 12 to 18 (including) or between 26 to 32 (including)
Hours = Target.Value
If Hours <> 0 Then
If Hours > 8 Then
Target.Value = 8
Target.Offset(0, 1).Value = Hours - 8
Exit Sub
Else
If Hours < 8 Then
Target.Offset(0, 2).Value = 8 - Hours
End If
Exit Sub
End If
End If
End Select
End If
End Sub
和
Sub Clear()
Range("B12:E18").Select
Selection.ClearContents
Range("G12:J18").Select
Selection.ClearContents
Range("B26:E32").Select
Selection.ClearContents
Range("C9").Select
Selection.ClearContents
MsgBox ("Content cleared")
End Sub
当我拨打第二个时,我会在Run time error 13 Type mismatch error
获得If Hours <> 0 Then
如果我手动清除范围,也会发生同样的情况。
我该如何防止这种情况?
答案 0 :(得分:0)
当同时更改多个单元格时(例如当您运行Clear
sub)时,Target
的{{1}}参数是包含所有已更改单元格的范围 - 该范围的Worksheet_Change
是一个二维数组值,而不是单个值,因此您无法直接将其与单个值进行比较(例如,测试它是否为零)。
最简单的方法是在.Value
为&gt; 1个单元格时退出。
Target
这也是处理清除范围的更简单方法:
Private Sub Worksheet_Change(ByVal Target As Range)
' check if target is in Column B or Column G
If Target.Cells.CountLarge > 1 Then Exit Sub '<<<<<<<<<<<<<<
If Target.Column = 2 Or Target.Column = 7 Then
Select Case Target.Row
Case 12 To 18, 26 To 32 'check if target row is 12 to 18 (including)
' or between 26 to 32 (including)
Hours = Target.Value
If Hours <> 0 Then
If Hours > 8 Then
Target.Value = 8
Target.Offset(0, 1).Value = Hours - 8
Exit Sub
Else
If Hours < 8 Then
Target.Offset(0, 2).Value = 8 - Hours
End If
Exit Sub
End If
End If
End Select
End If
End Sub