Access Tip – Setting Font Size Dynamically in a Label
Setting Font Size Dynamically in a Label
The following are some samples of VBA code that may prove useful.
Sometimes you want to set the font size of a label in a form or report depending on the length of the text to be displayed. For example, you may have a report that prints a person’s name in a fixed length label in the header. As names can vary in length, you want to use bigger font for shorter names and smaller for larger names.
The example below lists a sample set of font sizes for names ranging from under 27 characters to over 42 characters. The comments at the top list the font size for forms and the font size for reports. You will need to experiment for your own particular situation. First create the table at the top, then use those figures in the if statements.
To use the function store it in a module.
Assume you have a label called lblName in a form or report. Use the following in the form or report OnOpen event.
funSetFontSize Me.lblName.Caption ‘ Get the font size for the Name
Me.lblName.FontSize = lngTitleFontSize ‘ Set the font size for the Name
Public Function funSetFontSize(strName As String) ‘ Set the font size of the names in screens and reports Dim lngTextLength As Long ‘ Length of the text to be displayed ‘ The next two public values can be used anywhere in the application ‘ Max Chars -Form Font – Report Font On Error GoTo Error_funSetFontSize lngTextLength = Len(strName) If lngTextLength < 27 Then lngTitleFontSize = 20 End If If lngTextLength >= 27 And lngTextLength < =28 Then lngTitleFontSize = 16 End If If lngTextLength >= 30 And lngTextLength < =32 Then lngTitleFontSize = 14 End If If lngTextLength >= 33 And lngTextLength < =36 Then lngTitleFontSize = 13 End If If lngTextLength >= 37 And lngTextLength < =39 Then lngTitleFontSize = 12 End If If lngTextLength >= 40 And lngTextLength < =42 Then lngTitleFontSize = 12 End If If lngTextLength >= 43 Then lngTitleFontSize = 10 End If Exit_funSetFontSize: Error_funSetFontSize: End Function |