简体   繁体   中英

Excel 2016 VBA Runtime error 13

I wrote the code below to clear the cell in column D only if the value of the cell in in the corresponding row of column B changes to a value that is part of a specific list/range (B118:B124). If I change the cell in B to any value that is not part of that list, the cell in the corresponding row in D will not clear (that is what I want).

The code below works fine, except, if for example I want to delete 5 (adjacent) cells in column B at the same time, I get runtime error 13. Same is the case if I enter a new value in the first of the deleted/blank cells and then try to auto fill it down to the rest of deleted/blank cells. Basically, the code below seems to not work if I want to change multiple cells in B at the same time (autofill,...). If I only delete/change one cell (in B) at a time, it works just fine. Any help would be greatly appreciated. Thanks.

Private Sub Worksheet_Change (ByVal Target As Range)  

If Not Intersect(Target, Range("B:B")) Is Nothing Then
    If Application.WorksheetFunction.CountIf(Range("B118:B124"), Target) Then
        Range("D" & Target.Row).ClearContents
    End If
End If

End Sub

I think the issue is that COUNTIF is expecting a singular value, not a range containing values. Try this instead:

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Target, Range("B:B")) Is Nothing Then
    For Each cell In Range(Target.Address)
        If Application.WorksheetFunction.CountIf(Range("B118:B124"), cell) Then
            Range("D" & cell.Row).ClearContents
        End If
    Next cell
End If

End Sub

EDIT: Updated answer with everyone's contributions:

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Target, Range("B:B")) Is Nothing Then
    For Each cell In Target
        If Not Intersect(cell, Range("B:B")) Is Nothing Then
            If Application.WorksheetFunction.CountIf(Range("B118:B124"), cell) Then
                Application.EnableEvents = False
                    Range("D" & cell.Row).ClearContents
                Application.EnableEvents = True
            End If
        End If
    Next cell
End If

End Sub

When selecting a range, you must process each individually in this case. Loop the range in target and done.

Private Sub Worksheet_Change(ByVal Target As Range)
    For Each cell In Target
        If Not Intersect(cell, Range("B:B")) Is Nothing Then
            If Application.WorksheetFunction.CountIf(Range("B118:B124"), cell) Then
                Range("D" & cell.Row).ClearContents
            End If
        End If
    Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM