带代码的运行时错误13 - 清除单元格的内容

时间:2014-02-18 05:00:20

标签: excel-vba runtime-error vba excel

目前我正在运行一个电子表格,告诉我是否选择了一名员工。当我清除一个单元格上的内容时,我很好,但如果我一次清除多个单元格,则会出现运行时错误13.有没有办法删除此错误?

Sub Worksheet_Change(ByVal Target As Range)
Dim res As Variant
If Not Intersect(Target, Range("A5:A550")) Is Nothing Then
    res = Application.CountIfs(Range("A5:A550"), Target, _
            Range("M5:M550"), "Associate")
    If Not IsError(res) Then
        If res > 0 Then MsgBox "You have choosen an associate for this trip!"
    End If
End If
End Sub

2 个答案:

答案 0 :(得分:2)

未测试:

Sub Worksheet_Change(ByVal Target As Range)
Dim res As Variant, c as Range, rng as Range, i as long

Set rng = Application.Intersect(Target, Me.Range("A5:A550"))

If Not rng Is Nothing Then
    i=0
    For each c in rng.cells
        res = Application.CountIfs(Range("A5:A550"), c.Value, _
                                   Range("M5:M550"), "Associate")
        If Not IsError(res) Then 
            If res > 0 Then i = i + 1
        End If
    Next c

    If i > 0 Then 
       MsgBox "You have chosen an associate for " & _
                 IIf(i=1,"this trip!", i & " of these trips!")
    End If

End If

End Sub

答案 1 :(得分:0)

另一个对我有用的选项是在用户清除多个单元格或自动填充多个单元格的情况下退出Sub。

Dim rng As Range
Set rng = Target.Parent.Range("A5:A550")

If Target.Count > 1 Then Exit Sub
If Intersect(Target, rng) Is Nothing Then Exit Sub

// Put your code here
相关问题