VBA - Converting Datatypes

When combining data that is different type you can generated a Run-time error '13': Type mismatch.

To overcome this we can use the builtin functions for converting data from one datatype to another.

This i s basic example where are trying to add together a string and an integer. For strings the plus symbol combines the strings into one long string. For integers the numbers are added together and the results is combined. As these are different response the computer does not know what to do and creates an error.


This is the generated error:


To overcome this we can include the convert to string function "Cstr()" to create a situation where we are adding stings to other strings. 



Another alternative is to use a function that only applied to strings. for example strings can be combined with the "&" symbol.

Here is a list of the common data type conversions

Cstr - Converts a datatype into a string
Cint - Converts a datatype into an integer
Cbyte - Converts a datatype into a byte
Clng - Converts a datatype into a long
Csng - Converts a datatype into a single
Cdbl - Converts a datatype into a double
Ccur - Converts a datatype into a currency
Cdec - Converts a datatype into a decimal




Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.



Must Read Articles


VBA and Microsoft Excel - Getting the most out of excel with VBA programming
VBA and Microsoft Word - Getting the most out of word with VBA programming
Application Object - Using the applications features in your code.
Installing VBA and First Program - What do you need to start using visual basic application VBA.