Skip to content

Conditional Formatting on a Form Field

This article looks at using conditional formatting on a form field.

Q:  Tim Rundle writes:  “I have two fields that form part of a database.  Both are numeric.  In the forms area I obtain the average of the two fields and show the result as an unbound Field in the form.  That’s fine – all works OK until I try to add conditional formatting by VB code.  While my software lets me write the VB Code it does not display it at all.  So, question is, Can you denote Conditional Formatting on an unbound field in a Form?  If you can, could you please give me an example I can follow.”

A:  I would create the calculated field in the form’s record source query or SQL statement, so a form control can be bound to that calculated field.  The conditional formatting is done on the form control, not in code.  You can do conditional formatting in code, but that is mostly useful for reports, and in any case it is easier to just do it in the interface.  In case you do want to do the formatting in code, here is a sample (previously published in WAW 5.11):

Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)

 

   If Me![Sales] >= 10000 Then

      Me![txtSales].FontBold = True

      Me![txtSales].FontName = “Arial Black”

      Me![txtSales].FontSize = 12

      Me![txtSales].ForeColor = vbRed

      Me![txtSales].BackColor = vbYellow

      Me![imgGoldStar].Visible = True

   Else

      Me![txtSales].FontBold = False

      Me![txtSales].FontName = “Arial”

      Me![txtSales].FontSize = 9

      Me![txtSales].ForeColor = vbBlack

      Me![txtSales].BackColor = vbWhite

      Me![imgGoldStar].Visible = False

   End If

     

End Sub

 

For a form, instead of the Report_Detail event, you could put the code on a form event such as Current or AfterUpdate, or perhaps a control AfterUpdate event.

About this author

Office 2024 - all you need to know. Facts & prices for the new Microsoft Office. Do you need it?

Microsoft Office upcoming support end date checklist.