Conversion Functions


Conversion functions are used to convert a value from one format to another. An example would be converting a numeric value into a string or converting the string back into a numeric value. These functions are extremely useful for switching values between various formats. For example, you may have a four-figure number where you want the second digit on its own. One of the easiest ways to do this is to convert the number into a string and then use the Mid function to separate out that digit. You can then convert it back to a numeric for the purposes of performing further calculations.

Cstr

Cstr converts a value to a string. The following example will produce the string "1234":

 Cstr(1234) 

CInt

CInt converts a value or a string to an integer (2 bytes). There are no decimal places shown. Both of the following examples will give the value 123:

 CInt (123.45) 
CInt("123.45")

CInt does not work like the Int function and instead rounds to the nearest whole number instead of rounding down. If there are any non-numerical characters in the expression, you will get a Type Mismatch error.

CLng

CLng converts a value or a string to a long integer (4 bytes). There are no decimal places shown. Both of the following examples will return the value 123456789:

 CLng(123456789.45) 
CLng("123456789.45")

Note that CLng does not work like the Int function and rounds to the nearest whole number instead of rounding down. If there are any non-numerical characters in the expression, you will get a Type Mismatch error.

CDbl

CDbl converts a value or a string to a double precision floating point number (8 bytes) where decimal places are allowed:

 CDbl("123.56789") 

This will return the value 123.56789.

If there are any nonnumeric characters in the expression, you will get a Type Mismatch error.

Val

Val converts a string to a value. It is more forgiving than CInt or CLng because it will accept nonnumeric characters:

 Val("123") 

This will give the value 123. The following will give the value 123.45:

 Val("123.45") 

The next example will give the value 12:

 Val("12richard") 

The following will give the value 0, meaning there are no numeric characters to evaluate:

 Val("richard") 



Excel VBA Macro Programming
Excel VBA Macro Programming
ISBN: 0072231440
EAN: 2147483647
Year: 2004
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net