简体   繁体   中英

If 0 clear contents for multiple columns

I'm wondering how to make the following code work for multiple columns (D:P)? I've already tried adding & ":"P" & "65536" to the range, without success.

For i = 5 To Range("D" & "65536").End(xlUp).Row Step 1
If Application.WorksheetFunction.CountIf(Range("D" & i), "0") = 1 Then
Range("D" & i).ClearContents
End If
Next i 

您可以使用Range("D5:P65536").Replace What:=0,Replacement:=""可一次替换所有内容。

Maybe you are looking for sth like that. This will clear contents only if every cell in a row contains a 0.

Dim i As Long
Dim rg As Range

    For i = 5 To Range("D" & "65536").End(xlUp).Row Step 1
        Set rg = Range("D" & i & ":P" & i)
        If Application.WorksheetFunction.CountIf(rg, "0") = 13 Then
            rg.ClearContents
        End If
    Next i

Loop through the actual column and use the Find() method to perform your search. If your value exists in that range (range = column), then you can clear the contents that way.

Sub test()

    ' Just for illustration on the columns
    Const D& = 4:   Const P& = 16

    Dim ws As Worksheet, col As Long
    Set ws = ThisWorkbook.Worksheets(1)

    For col = D To P
        If Not ws.Columns(col).find(What:="0", LookAt:=xlWhole) Is Nothing Then
            ws.Columns(col).ClearContents
        End If
    Next col

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