简体   繁体   中英

How to delete entire row except column A in VBA loop?

I'm trying to highlight the entire row grey if the value in column A begins with "ABC" as well as delete everything right of that cell. Any ideas on how to do this?

Dim DataRange As Range
Set DataRange = Range("A1:U" & LastRow)

Set MyRange = Range("A2:A" & LastRow)

For Each Cell In MyRange
If UCase(Left(Cell.Value, 3)) = "ABC" Then
    Cell.EntireRow.Interior.ColorIndex = 15


Else


End If
Next

Here is pretty straightforward approach:

Dim lastRow As Long
Dim row As Long
Dim temp As String

' insert your sheet name here
With ThisWorkbook.Worksheets("your sheet name")

    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    ' you can change the starting row, right now its 1
    For row = 1 To lastRow

        ' store whats in col A in a temporary variable
        temp = Trim(CStr(.Range("A" & row).Value))

        ' if col A isn't 'ABC' clear & grey entire row
        If UCase(Left(.Range("A" & row).Value), 3) <> "ABC" Then

            .Rows(row).ClearContents
            .Rows(row).Interior.ColorIndex = 15

            ' place temp variable value back in col A and make interior No Fill
            .Range("A" & row).Value = temp
            .Range("A" & row).Interior.ColorIndex = 0

        End If
    Next
End With

Here is another example; you stated "clear everything to the right" so I added offset to clear the contents of the cells not in column A.

Dim x As Long

For x = 1 To Cells(Rows.Count, 1).End(xlUp).Row
    If UCase(Left(Cells(x, 1).Value, 3)) = "ABC" Then
        Range(Cells(x, 1), Cells(x, Columns.Count).End(xlToLeft)).Interior.ColorIndex = 15
        Range(Cells(x, 1).Offset(, 1), Cells(x, Columns.Count).End(xlToLeft)).ClearContents
    End If
Next x  

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