Enter value as a percent

        2 votes: *****     6,359 views      No comments
by Allen Browne, 31 May 2005    (for Access 95+)

MS-Access Tips for Casual Users

Provided by allenbrowne.com, May 2005. Updated May 2006.


Enter value as a percent

Update: In Access 2007, if a field or control is formatted as Percent, the % is added automatically. This code is unnecessary.

When you set a field's Format property to "Percent" and enter 7, Access interprets it as 700%.
How do you get it to interpret it as 7% without having to type the percent sign for every entry?

Use the AfterUpdate event of the control to divide by 100.
But then if the user did type "7%", your code changes it to 0.07%.
We need to divide by 100 only if the user did not type the percent sign.

To do that, examine the Text property of the control.
Unlike the control's Value, the Text property is the text as you see it.
(In Access, unlike pure VB, the Text is available only for the control that has focus.)

Using the code

To save the function in your database:

  1. Choose the Modules tab of the Database window.
  2. Click New to open a module.
  3. Copy the code below, and paste into your module.
  4. Save the module with a name such as "Module1".

To apply to a text box named "Text23":

  1. Open the form in design view.
  2. Right-click the text box, and choose Properties.
  3. Set the After Update property of the text box to:
        =MakePercent([Text23])

Public Function MakePercent(txt As TextBox)
On Error GoTo Err_Handler
    'Purpose: Divide the value by 100 if no percent sign found.
    'Usage:   Set the After Update property of a text box named Text23 to:
    '             =MakePercent([Text23])

    If Not IsNull(txt) Then
        If InStr(txt.Text, "%") = 0 Then
            txt = txt / 100
        End If
    End If

Exit_Handler:
    Exit Function

Err_Handler:
    If Err.Number <> 2185 Then  'No Text property unless control has focus.
        MsgBox "Error " & Err.Number & " - " & Err.Description
    End If
    Resume Exit_Handler
End Function

Home Index of tips Top

Rate this article:  Your rating: PoorYour rating: Not so goodYour rating: AverageYour rating: GoodYour rating: Excellent


This is a cached tutorial, reproduced with permission.

Have your say - comment on this article.

What did you think of 'Enter value as a percent'?

No comments yet.

Why not be the first to comment on this article?!

Have your say...

Name
E-mail (e-mail address will be kept private)
Comments


Comments require approval before being displayed on this page (allow 24 hours).