如何在VBA循环中删除除A列以外的整个行?

时间:2019-01-16 16:57:31

标签: excel vba

如果列A中的值以“ ABC”开头,我想突出显示整个行为灰色,并删除该单元格的所有内容。有关如何执行此操作的任何想法?

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

2 个答案:

答案 0 :(得分:1)

这是非常简单的方法:

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

答案 1 :(得分:0)

这里是另一个例子;您说“清除右边的所有内容”,所以我添加了偏移量以清除不在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