Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, and 2013. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Converting Numbers to Strings.

Converting Numbers to Strings

by Allen Wyatt
(last updated April 3, 2018)

9

You already know that you can use variables in your macros, and that there are two very basic types of variables: string variables (containing characters) and numeric variables (containing numeric values). You can quickly and easily convert a number into a string in your macros. This is the done with the Str() function. The way you use this function is as follows:

A = Str(B)

In this syntax, if B is equal to 5, then when completed, A will be " 5"; if B is -4, then A would be "-4". Notice the leading space when converting positive numbers. This may not provide satisfactory results for some subroutines. Instead, you should create a function that returns a stripped-down version of the string. The following function does just that:

Function ToNum(X as Variant) as String
    Dim A as String

    A = Trim(Str(X))
    ToNum = A
End Function

The reason that the value passed to the VBA function (X) is defined as a Variant is that you can then pass any type of numeric value.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (9749) applies to Microsoft Excel 2007, 2010, and 2013. You can find a version of this tip for the older menu interface of Excel here: Converting Numbers to Strings.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Disappearing AutoText Entries

Some detective work on disappearing AutoText entries in Word.

Discover More

Controlling the Display of Toolbars

The various toolbars available in Excel are indispensable when it comes to easily accomplishing tasks. Here is a concise ...

Discover More

Repeating Actions

Need to repeat an action a whole bunch of times? You can do it a time or two using keyboard shortcuts, but you'll need a ...

Discover More

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!

More ExcelTips (ribbon)

Debugging a Macro

Part of writing macros is to make sure they work as you expect. This involves a process known as debugging. Here's how ...

Discover More

Reorganizing Data

If you need to consolidate a single column of data into multiple columns of data, you'll love this macro. It provides a ...

Discover More

Stopping a Checked Box from being Unchecked

When creating user forms for use in Excel, you are provided with a range of controls you can add, including check boxes. ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 6 - 3?

2018-04-05 03:49:44

Philip

@Alan, thanks for your feedback. The sendkeys seems to work just fine, it's just a shame that I have to resort to it ...

@Willy, sometimes it's not possible to fully control the format in which information is provided to my workbooks as it's often coming from outside sources. Where I do have that control, I am forcing number or text format on the information when using it in formulas (depending on the case).

The fact that the look-up formula's will work once "enter" is pressed, but not before that, tells me that there is a bug in Excel (even setting the format of the cell to "text" is ignored, and I can't insert a single quotation mark in the information at the source), and even though Excel tries its best to cope, obviously it's not good enough (since a simple "enter" key event "wakes up" the right functionality, as Alan describes it.

So I'll continue working around it in this case with the sendkeys ...

Thank you both for your feedback and suggestions


2018-04-04 04:19:15

Alan Elston

@ Philip
I have experienced something very similar to what you have described. That is to say I have had to hit Enter to get something to behave as it should. In that case it appeared that a number was being held in some strange text form which prevented it being used in other things. Somehow hitting Enter seemed to wake something up. It did appear to me to be something strange, possibly a Bug.
I don’t have that file and info to hand just now, but I think I came up with a solution. When I stumble over it again I will post a note here. It may be of some help.

I do not have much experience with sending the equivalent of a Key stroke with VBA. But I have heard that it is very unwise as it often cause other strange problems and potential crashes. I myself used a VBA code once to do Ctrl+g from the VB Editor to get the immediate window up. But I stopped using it as it was frequently the cause of a bad system crash.

But here is some info on the Application.SendKeys Method

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-sendkeys-method-excel

http://www.contextures.com/excelvbasendkeys.html

Alan Elston


2018-04-03 14:18:48

Willy Vanhaelen

@Philip
"a string consisting of numerals, often behaves erratically in formulas". In fact it doesn't because it is not a number but a string. it's not a good idea to use numeric references to "string numbers" in formulas. Excel/vba does it's best to cope with it but you are never 100% sure. To avoid problems it's best to convert those numbers, stored as text, to numbers (see: https://support.office.com/en-us/article/Convert-numbers-stored-as-text-to-numbers-40105f2a-fe79-4477-a171-c5bad0f0a885).

To reference such number strings, you can also use VALUE(text) in Exel formulas or Val(string) in vba.


2018-04-03 07:03:01

Philip

My problem is rather that cells that have been formatted as TEXT but contain a string consisting of numerals, often behaves erratically in formulas. I have a look-up formula that wil return an error unless I go into the cell with the look-up value and press enter. So, I am not changing ANYTHING to the cell, just sending en "enter" key event to it, to fix the problem. This is a bug in Excel I believe. How do I get around that other than my current solution (which is to include in my macros a send key event to mimic the "enter" key event ...)


2018-03-03 12:09:51

Willy Vanhaelen

Oops: remove the last bracket: ToNum = CStr(X)


2018-03-03 12:05:48

Willy Vanhaelen

Or even:

Function ToNum(X as Variant) as String
ToNum = CStr(X))
End Function


2018-03-03 05:44:22

Willy Vanhaelen

You can even make it a tiny one-liner:

Function ToNum(X as Variant) as String
ToNum = Trim(Str(X))
End Function


2018-03-02 02:52:54

Dave Alan

A simple, but useful alternative way of doing this which i had not thought of doing, thanks.


2014-08-04 08:16:40

Bryan

To quote myself from a comment on this post from almost exactly a year ago: "Why reinvent the wheel? CStr does the same as ToNum. Or if you want to change the format (perhaps set a decmial), you can use Format instead.

The whole thing is generally superfluous anyway; there aren't a lot of circumstances where you HAVE to coerce a number to be a string. For instance, "Total : " & Number will give you the same result as "Total : " & CStr(Number)."


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.