简体   繁体   中英

VBA Excel to highlight range on another worksheet

Long time lurker here, I've finally been stumped trying to code some VBA to highlight from columns B to S on another worksheet, for all rows that have a value in column S greater than H10 on the other worksheet. This code works fine:

Dim i As Long
For i = 2 To Rows.Count
If Worksheets("Initial Data").Cells(i, 19).Value > Worksheets("Inputs").Range("H10").Value Then
Worksheets("Initial Data").Cells(i, 19).Interior.ColorIndex = 4
End If
Next i
Worksheets("Initial Data").Activate

This will highlight each cell in column S that is required. What I want to do is highlight cells from B to S, something like this:

Dim i As Long
For i = 2 To Rows.Count
If Worksheets("Initial Data").Cells(i, 19).Value > Worksheets("Inputs").Range("H10").Value Then
Worksheets("Initial Data").Range(.Cells(i, 2), .Cells(i, 19)).Interior.ColorIndex = 2
End If
Next i
Worksheets("Initial Data").Activate

...but it doesnt work, I get a runtime error. This is so frustrating as I've done the bulk of the hard stuff!

Oh and before anyone suggests conditional formatting, the data the sub reads from is freshly pasted each time, so thats a no no. thanks for any input!

Try remove dot before .Cells(i, 2) vba dont know which cells you mean

change Worksheets("Initial Data").Range(.Cells(i, 2), .Cells(i, 19)).Interior.ColorIndex = 2 to Worksheets("Initial Data").Range(Cells(i, 2), Cells(i, 19)).Interior.ColorIndex = 2

or use With -> msdn :

With Worksheets("Initial Data")
    .Range(.Cells(i, 2), .Cells(i, 19)).Interior.ColorIndex = 4
End With

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