简体   繁体   中英

Conditional Format Shape Fill Based on Cell Value

I hate to ask this question because I don't know where to start so I don't have any code right now. I've seen some stuff about the topic but can't find what I'm looking for.

Table is 5 column (ID + Bolt count) x 13 rows (ID)

I have four shapes (Oval4-Oval7) that I would like to change from red/orange/green based on four corresponding cells (options for those cell values are: empty, installed, torqued).

The shapes would also change color based on a chosen ID (1-13) in the first column.

So if you put your cursor on ID 2 cell, the shapes would change color based on the values in columns 2-5 from the same row.

Is this too overly complex?

I will continue to work on it myself. Just figured I would start here.

Thanks for your time.

Below code works but how do I apply it to the entire table?

 Private Sub Worksheet_Change(ByVal Target As Range)
 If Range("d12") = "Empty" Then
 ActiveSheet.Shapes.Range(Array("Shape1")).Select
 Selection.ShapeRange.Fill.ForeColor.RGB = RGB(255, 0, 0)
 Else
 If Range("d12") = "Installed" Then
 ActiveSheet.Shapes.Range(Array("Shape1")).Select
 Selection.ShapeRange.Fill.ForeColor.RGB = RGB(255, 155, 0)
 Else
 If Range("d12") = "Torqued" Then
 ActiveSheet.Shapes.Range(Array("Shape1")).Select
 Selection.ShapeRange.Fill.ForeColor.RGB = RGB(0, 255, 0)
 End If
 End If
 End If
 End Sub

在此处输入图像描述

In the sheet code module:

Private Sub Worksheet_Change(ByVal Target As Range)
    ResolveSelection Target.Cells(1)
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    ResolveSelection Target.Cells(1)
End Sub

'Is the selected/changed cell in one of the two tables?
'  If Yes get the full row for that cell and pass to SetRow
Sub ResolveSelection(Target As Range)
    Dim r, rng As Range
    For Each r In Array("B3:G14", "J3:O14") 'my 2 test tables
        Set rng = Application.Intersect(Target, Me.Range(r))
        If Not rng Is Nothing Then
            'get the whole row of the table
            Set rng = Application.Intersect(Target.EntireRow, Me.Range(r))
            SetRow rng
            Exit Sub
        End If
    Next r
End Sub

'set the coloring based on the row 'rw'
Sub SetRow(rw As Range)
    Dim i As Long, shp As Shape
    Debug.Print rw.Address
    For i = 1 To 4
        Set shp = rw.Parent.Shapes("Shape" & i)
        shp.Fill.ForeColor.RGB = GetColor(rw.Cells(2 + i).Value)
    Next i
End Sub

'get the color for a given state
Function GetColor(v As String) As Long
    Select Case v & ""
        Case "Empty", "": GetColor = vbRed
        Case "Installed": GetColor = RGB(255, 155, 0)
        Case "Torqued": GetColor = vbGreen
        Case Else: GetColor = vbWhite
    End Select
End Function

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