Skip to content

Listbox Line Coloring

A reader wants to know if it’s possible to color every other line of a listbox.

Q:  Martin wants to know if there is a way to color every other line of a listbox.

A:  Not as far as I know, but it is possible to color cells in a datasheet subform (to color an entire line, just apply the same condition to all columns).  See the Datasheet Cell color Demo form in the database for Access Archon #118 for an example of this technique, which uses Conditional Formatting to color one cell in a datasheet depending on a condition.  To color every other row yellow, I used the condition

CLng([ContactID]) Mod 2=0

The Mod operator divides one number by another and returns the remainder – so it is a handy way to distinguish odd from even numbers.  (Editor’s note: Helen’s use of Mod is a very fast and elegant solution to the alternating or odd/even requirement – far better than others we’ve seen over the years!)

For each control in the datasheet, resulting in every even-numbered row being yellow (of course, the alternate row coloring would break down if there were gaps in the numbering, as can happen with an AutoNumber field).  Here’s the Conditional Formatting dialog.


An expression used to color every other row in a datasheet subform

You can shade or color every other row of an Access report using the Mod operator and the obscure CurrentRecord property in the report’s Detail_Format section, as in the following code from my book Access 2002 Inside-Out:

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

 

   Const vbLightGrey = 12632256

 

   If Me.CurrentRecord Mod 2 = 0 Then

      Me.Section(acDetail).BackColor = vbLightGrey

   Else

      Me.Section(acDetail).BackColor = vbWhite

   End If

 

End Sub

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.