Andreas Hermle
asked on
Get the last column in excel range
Dear Experts:
below macro applies alternate shading from Row 2 downwards.
Could somebody help me tweak the code as follows:
- the last column is not be hard coded (see line 11)
- the very first row is to be shaded RGB (240, 240, 240) and the font color is to be 'white' (RGB 0, 0, 0)
Help is very much appreciated. Thank you very much in advance.
Regards, Andreas
below macro applies alternate shading from Row 2 downwards.
Could somebody help me tweak the code as follows:
- the last column is not be hard coded (see line 11)
- the very first row is to be shaded RGB (240, 240, 240) and the font color is to be 'white' (RGB 0, 0, 0)
Help is very much appreciated. Thank you very much in advance.
Regards, Andreas
Sub AlternateRowColors()
Dim lastRow As Long
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Dim lColumn As Long
lastRow = ws.Range("A1").End(xlDown).Row
'D is not to be hard coded but the last column (which is different on every worksheet) should adjust according to the used range
For Each Cell In ws.Range("A2:D" & lastRow)
If Cell.Row Mod 2 = 1 Then
Cell.Interior.Color = RGB(240, 240, 240)
Else
Cell.Interior.ColorIndex = xlNone
End If
Next Cell
Next ws
End Sub
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
@Bill
Line#15 should be like below...
Line#15 should be like below...
For Each Cell In ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, lastCol))
Corrected. That is best practice, agreed, I think in my simple test it wasn't needed but should be there for scalability.
~bp
~bp
ASKER
Great job Subodh, exactly how I wanted it. Thank you very much.
I am afraid to tell you Bill, that your code throws an error message, Subodh corrected it. You were very close.
Anyhow, thank you very much for your great, professional and swift help.
Regards, Andreas
I am afraid to tell you Bill, that your code throws an error message, Subodh corrected it. You were very close.
Anyhow, thank you very much for your great, professional and swift help.
Regards, Andreas
You're welcome Andreas! Glad I could help.
Open in new window
~bp