根据表中存储的值更改表单行的颜色

时间:2015-07-02 09:09:22

标签: vba ms-access userform

使用基于Access的应用程序。需要根据存储在这些字段中的值更改表单的某些特定行的颜色("一行"每行的字段需要更改)。例如,当我们打开表单时,我们需要在某行的字段中看到颜色为绿色,其中我们有值1.如果此字段的值为2,我们需要看到颜色为橙色,如果是3则是红色的。

表单

的输出示例
ID   Criteria
201  1        --> the cell containing 1 should be colored in green
203  3        --> the cell containing 3 should be colored in red
204  3
205           --> the cell that contains nothing should be kept uncolored
206  1        
207  2

注意:表格打开时,值(1,2和3)已经可用,它们也存储在表格中。

1 个答案:

答案 0 :(得分:4)

为了解决这个问题,我使用了条件格式 (我正在使用Microsoft Office Access 2007)。

以下是相应的代码。

Option Compare Database
Option Explicit

Const GreenG As Byte = 1

Const OrangeO As Byte = 2

Const RedR As Byte = 3


Private Sub StartCondFormatting()

Dim objFrc As FormatCondition

    Const orange As Long = 42495

    Const green As Long = 25600

    Const red As Long = 255

    Dim ctl As Control



    For Each ctl In Me.Controls

        If ctl.Tag = "Conditional" Then

            With ctl

                'Remove format conditions

                .FormatConditions.Delete



                'Create three format objects and add them to the FormatConditions

                Set objFrc = .FormatConditions.Add(acExpression, acEqual, "[fieldName] = " & GreenG)

                Set objFrc = .FormatConditions.Add(acExpression, acEqual, "[fieldName] = " & OrangeO)

                Set objFrc = .FormatConditions.Add(acExpression, acEqual, "[fieldName] = " & RedR)



                'Specify the formating conditions

                .FormatConditions(0).BackColor = green

                .FormatConditions(0).Enabled = True

                .FormatConditions(1).BackColor = orange

                .FormatConditions(1).Enabled = True

                .FormatConditions(2).BackColor = red

                .FormatConditions(2).Enabled = True

            End With

        End If

    Next ctl

    Set objFrc = Nothing


    End Sub



Private Sub Form_Load()
StartCondFormatting        
End Sub

For more information on conditional formatting.