To convert a string to a number in Visual Basic, we use this:

Dim MyNumber as Integer
Dim MyString as String = "32"
MyNumber = MyString

It's as simple as that!

NOTE: This can be dangerous. Some strings may not convert properly, causing a runtime error.

If you find this risky, you can force safe conversions by adding "Option Explicit On to the top of your VB page.

To convert correctly, we can use CType. Some other examples of CType are:

  • CStr(arg) - Converts argument to a string.
  • CInt(arg) - Converts argument to an integer.
  • CBool(arg) - Converts argument to a boolean.
  • Val(arg) - Converts argument to an integer. This one is a bit nicer because if the argument has no numeric value, it will simply return a "0" rather than an error.

If you are using .NET, you can use some of the built in functions, as well. Since .NET rightly views all variables as objects, any object (or variable) has its own premade functions. For example, you could convert a number to a string by using the ToString() function. Here is an example:

Dim MyNumber as Integer = 4
Dim MyString as String = ""
MyString = MyNumber.ToString()

After this code has compiled, MyString would have the value "4"

Next we will continue to discuss the built in functions in VB.NET!

Previous Next

Startup Discount
Small Business?
Contact us for an Enormous Discount!