An upgrade to the Text() function in Excel


Many of us are familiar with the Text() function. It comes in handy when you set up excel to draft reports for you. It converts a numeric value stored in a cell to a string based on  the format specified by the user. The only thing I hate about that function is that you have to specify the format every time you use it. Another drawback is, the format of the text is not linked to the cell formatting of the cell that is being referred to. For instance, if you later decide to change the cell formatting of a cell, you also have to change the Special-Format-String argument in the Text() function.

Wouldn’t it be great if there were a function that formats the string based in the cell’s format? Check out the code below.

This function first tries to use the ‘NumberFormatLocal’ property, and moves on to use the ‘’NumberFormat’ property if it encounters an error. The function is set to be Volatile by default. However, the user has the option to make it a non-volatile function if the workbook is considerably large. Click here to read more on Volatile functions.

'===================================================================
'Function to convert a numeric value to a string based in the
'cell formatting
'Author     : Ejaz Ahmed
'Date       : 14 November 2013
'Website    : https://strugglingtoexcel.wordpress.com/
'===================================================================
Function AutoText(ByRef WhichCell As Range, _
                    Optional ByVal ForceVolatile = True) As Variant

'Set to Volatile by default, the user could also choose for the
'function to be non-volatile
Application.Volatile (ForceVolatile)

'Return a reference error if the range refers to more than one cell
If WhichCell.Count > 1 Then
    AutoText = CVErr(xlErrRef)
    Exit Function
End If

On Error Resume Next
'use the NumberFormatLocal property if exists
AutoText = Application.WorksheetFunction.Text(WhichCell.Value2, WhichCell.NumberFormatLocal)
'if excel encounters an error, use the NumberFomat property
If Not Err.Number = 0 Then
    AutoText = Application.WorksheetFunction.Text(WhichCell.Value2, WhichCell.NumberFormat)
    Err.Clear
End If
On Error GoTo 0

End Function
Advertisements

2 thoughts on “An upgrade to the Text() function in Excel

  1. Pingback: Concatenate Range and Retain Formatting | Struggling To Excel

If you liked it, let me know. If you didn't make sure you let me know!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s