Programming macro to color rows
I am trying to program a macro that colors the rows where it finds a 0 value in the current column. I am unsure how to fix it though because it only does the first Range selection to the right ignoring the rest.
How can I tell the command to select all cells to the right of the current one up to Column T?
Sub FindAndColor()
'
' FindAndColor Macro
'
' Keyboard Shortcut: Ctrl+Shift+D
'
Cells.Find(What:="0", After:=ActiveCell, LookIn开发者_运维知识库:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Style = "Bad"
End Sub
Also, I would like it to put me in the cell below the current one? What needs to go in place of "A1" so that it is the current cell and not A1.
Range("A1").Offset(0,1)
Any help appreciated,
Ted
Are you trying to loop through all the rows of the sheet and change the formatting of any row where the currently selected column is 0? If so, the below will work without using .Select (.Select is evil).
Sub FindAndColor2()
'This code will find each row with 0 in the currently selected column
' and color the row from column 1 to 20 (A to T) red and set the
' font to bold.
Dim row As Long
Dim col As Long
'Get the column of the current selection
col = Selection.Column
'Loop through every row in the active worksheet
For row = 1 To ActiveSheet.UsedRange.Rows.Count
'If the cell's value is 0.
If ActiveSheet.Cells(row, col).Text = 0 Then
'Put your formatting inside this with. Note that the 20 in .cells(row, 20)
' is column T.
With ActiveSheet.Range(ActiveSheet.Cells(row, 1), ActiveSheet.Cells(row, 20))
.Interior.Color = vbRed
.Font.Bold = True
.Style = "Bad"
'Other formatting here
End With
End If
Next row
End Sub
I know you asked something about VBA, but in a case like this, you might want to consider using conditional formating. If it's not applicable, you can go with
Range([Fill Me]).Interior.Color = vbRed
or
Cells([Fill Me]).Interior.Color = vbRed
精彩评论