简体   繁体   中英

Coloring cells in Excel only of Last Column till Last Row and Last Row till Last Column

I would like to highlight the entire row of the last cell till its last column and vice-versa for the entire column

I've used EntireRow and EntireColumn method and found that it is bit flawed for my approach as it colors whole row and column.

Option Explicit
Sub Range_End_Method()
'Finds the last non-blank cell in a single row or column
Dim lRow As Long
Dim lCol As Long
Dim c As Range

'Find the last non-blank cell in column A(1)
lRow = Cells(Rows.Count, 1).End(xlUp).Row

'Find the last non-blank cell in row 1
lCol = Cells(1, Columns.Count).End(xlToLeft).Column

Cells(lRow, lCol).EntireRow.Interior.Color = RGB(174, 240, 194)
Cells(lRow, lCol).EntireColumn.Interior.Color = RGB(174, 240, 194)
End Sub

Give this a try:

Range(Cells(lRow, 1), Cells(lRow, lCol)).Interior.Color = RGB(174, 240, 194)
Range(Cells(1, lCol), Cells(lRow, lCol)).Interior.Color = RGB(174, 240, 194)

I would advise to declare and use a worksheet variable (at least), in case you want to call this sub from a different sheet and/or a different workbook.

Having said that, this is how your sub would look afterwards:

Option Explicit

Sub Range_End_Method()
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("sheet name")
    With ws
        Dim lRow As Long: lRow = .Cells(Rows.Count, 1).End(xlUp).Row 'Find the last non-blank cell in column A(1)
        Dim lCol As Long: lCol = .Cells(1, Columns.Count).End(xlToLeft).Column 'Find the last non-blank cell in row 1

        .Range(.Cells(lRow, 1), .Cells(lRow, lCol)).Interior.Color = RGB(174, 240, 194)
        .Range(.Cells(1, lCol), .Cells(lRow, lCol)).Interior.Color = RGB(174, 240, 194)
    End With
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