Forum Discussion
hrh_dash
Sep 03, 2022Iron Contributor
VBA to select one column to another column
How do i write a macro to select one column to another one column with values?
For example; i have values from cell A1 to N1, would like to select column from A to N instead of just column N
This is my code so far which only highlights column N.
Dim ws As Worksheet
Dim lastRow As Long
Dim i As Long
Dim lastColumn As Integer
Dim j As Long
Set ws = ThisWorkbook.Sheets("TCA_consumer")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
For i = 2 To lastRow
If Cells(i, 14) = "Retain" Then
For j = 1 To lastColumn
Cells(i, lastColumn).Interior.ColorIndex = 4
Next j
Else
For j = 1 To lastColumn
Cells(i, lastColumn).Interior.ColorIndex = 5
Next j
End If
Next i
Appreciate the help in advance.
hrh_dash To improve performance of macro we must try to avoid too many loops. Give a try on below codes.
Sub HighlightCells() Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim lastColumn As Integer Dim j As Long Set ws = ThisWorkbook.Sheets("TCA_consumer") lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column For i = 2 To lastRow If Cells(i, 14) = "Retain" Then Range("A" & i, Cells(i, lastColumn)).Interior.ColorIndex = 4 Else Range("A" & i, Cells(i, lastColumn)).Interior.ColorIndex = 5 End If Next i End Sub
- Harun24HRBronze Contributor
hrh_dash To improve performance of macro we must try to avoid too many loops. Give a try on below codes.
Sub HighlightCells() Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim lastColumn As Integer Dim j As Long Set ws = ThisWorkbook.Sheets("TCA_consumer") lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column For i = 2 To lastRow If Cells(i, 14) = "Retain" Then Range("A" & i, Cells(i, lastColumn)).Interior.ColorIndex = 4 Else Range("A" & i, Cells(i, lastColumn)).Interior.ColorIndex = 5 End If Next i End Sub