Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

excel - Color cells based on their value - VBA

I need to be able to colour code cells based on their values in VBA as conditional formatting will not handle the number of conditions I will ultimately require. For instance if the value of B is "Decommission" then I would like to check the values of C, D and E and colour code them in relation to the value of B. Unfortunately, the code I've written is running through the whole sheet and colour coding everything in the range based on the first value. I've defined 2 x ranges (all_data and response) I know what's wrong but I don't know how to tell the code to only restrict the formatting to the value of the row.. Any help would be greatly appreciated.

Sub Formatter()

Dim All_Data As Range
Dim Response As Range

Dim MyCell As Range
Dim MyCell2 As Range

Set All_Data = Range("All_Data")
Set Response = Range("Response")

For Each MyCell In All_Data
If MyCell.Value = "Decommission" Then
   MyCell.Interior.ColorIndex = 3
         For Each MyCell2 In Response
            If MyCell2.Value = "Yes" Then
                MyCell2.Interior.ColorIndex = 4
            End If
         Next
End If
Next

End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

Sub Formatter()

Dim All_Data As Range
Dim Response As Range

Dim MyCell As Range
Dim MyCell2 As Range

Set All_Data = Range("All_Data")
Set Response = Range("Response")

For Each MyCell In All_Data
If MyCell.Value = "Decommission" Then
   MyCell.Interior.ColorIndex = 3
         For Each MyCell2 In Intersect(Response, ActiveSheet.Rows(MyCell.Row))
            If MyCell2.Value = "Yes" Then
                MyCell2.Interior.ColorIndex = 4
            End If
         Next
End If
Next

End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...