简体   繁体   中英

EXCEL VBA change selected cells to colour

I am trying to write a peice of VB that will look at a run an iff statement and then if true change the colour of the row that was true. Currently I can get it only to change the colour for one cell.

the VB looks like this.

Sub Blue()

Set A = Sheets("Analysis")

Dim d
Dim j
d = 1
j = 1

Do Until IsEmpty(A.Range("B" & j))


If (A.Range("F" & j) <> A.Range("G" & j)) Or (A.Range("H" & j) <> A.Range("I" & j)) Then

d = d + 1
A.Range("B" & j).Interior.ColorIndex = 28

End If

j = j + 1
Loop

End Sub

That works. When i try to change this to highlight a selection of cells in the table. i get a 1004 run time error Sub Blue()

Set A = Sheets("Analysis")

Dim d
Dim j
d = 1
j = 1

Do Until IsEmpty(A.Range("B" & j))


If (A.Range("F" & j) <> A.Range("G" & j)) Or (A.Range("H" & j) <> A.Range("I" & j)) Then

d = d + 1
A.Range("A:U" & j).Interior.ColorIndex = 28

End If

j = j + 1
Loop

End Sub

I have spent loads of time looking on the internet and cant find any answeres to why this does not work. any help would be appreicated.

I am using VB as this will be part of a much larget peice of VB.

To change colour of columns A to U use this:
A.Range("A" & j & ":U" & j).Interior.ColorIndex = 28 - in your line you are missing the row for column A.

To change colour of the entire row use this:
A.Range("B" & j).EntireRow.Interior.ColorIndex = 28

我没有通过任何PC进行测试,但是您可以尝试

A.Range("A:U").rows(j).Interior.ColorIndex = 28

A range for more then one cell should be in this format "A1:U1", your code is equal to "A:U1".

You could code like this:

A.Range("A" & j & ":U" & j).Interior.ColorIndex = 28

I prefer this code:

A.Range(Cells(j, 1), Cells(j, 21)).Interior.ColorIndex = 28

Good Luck

Jorgen Unger

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