简体   繁体   中英

Color a column by searching a particular text in A:A

Assist me with a VBA to color column from A:G, by searching a specific text, say 'UK'in Column A 在此处输入图片说明

a very short and dirty and rude code is the following:

Sub ColorColumns()
    On Error Resume Next
    Range("A1", Cells(Rows.Count, 1).End(xlUp)).Find(what:=Application.InputBox("Text to search:", , , , , , , 2), LookIn:=xlValues, lookat:=xlWhole).Resize(, 7).Interior.ColorIndex = 6
End Sub

You can use the following code. Remember to keep the sheet containing the table active when running the code. Alternatively, you can specify the sheet explicitly when setting the ws variable.

Sub SelectivelyColorARowRed()

    Dim ws As Worksheet
    Set ws = ActiveSheet
    lng_lastrow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    Dim k As Long

    For k = 2 To lng_lastrow
        If Trim(ws.Cells(k, 1).Value) = "UK" Then
        'you can also apply UCase if you want the search to be case-insensitive
        'like: If UCase(Trim(ws.Cells(k, 1).Value)) = UCase("Uk") Then
            ws.Range(Cells(k, 1), Cells(k, 7)).Interior.ColorIndex = 22
        End If
    Next k

End Sub

Try this. Code1 works on every sheet in the workbook but if you like for this to work for the active sheet then try Code2. For Code2 remember to write the correct sheets name. Hope it helps.

Here you can choose an index color: https://stackoverflow.com/a/25000926/7238313

Code1:

Sub rowhighlight()
Dim sht As Worksheet
Dim nlast As Long

For Each sht In ActiveWorkbook.Worksheets
    sht.Select
    nlast = Cells(Rows.Count, "A").End(xlUp).Row

        For n = nlast To 2 Step -1
            If sht.Cells(n, "A").Value = "UK" Then
                sht.Range("A" & n, "G" & n).Interior.ColorIndex = 37
                'different color number place here----------------^
            End If
        Next n
     Next sht
 End Sub

Code2:

Sub rowhighlight()
Dim nlast As Long

Sheets("sheetname").Activate
Set sht = ActiveWorkbook.ActiveSheet
nlast = Cells(Rows.Count, "A").End(xlUp).Row

    For n = nlast To 2 Step -1
        If sht.Cells(n, "A").Value = "UK" Then
            sht.Range("A" & n, "G" & n).Interior.ColorIndex = 37
            'different color number place here----------------^
        End If
    Next n
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