Visual Basic Variables
Variables allow us to store and retrieve data. Variables are storage locations and the data is held in the computer’s memory (RAM). In Visual Basic, variables start with the Dim keyword.
Syntax
Dim <variable name> As <data type>
VB supports a number of data types; the common ones are:
Data Type | Description |
---|---|
Integer | Whole Numbers |
Floating Point | Numbers with decimals e.g. 5.2 |
Boolean | True Or False |
Double | Floating Point numbers but more accurate |
Char | Single characters |
Variables can start with uppercase or lowercase characters.
Create a new VB Console Application and name it Variables. Between the Sub Main() and End Sub, type the following:
Sub Main() Dim myNumber As Integer myNumber = 5 Console.WriteLine(myNumber) Console.ReadLine() End Sub
Hit F5 or click the green play icon on the toolbar. You should see the result 5.
Code Explained
- First we use the Dim keyword to create the variable myNumber
- Next we assign the value 5 to myNumber
- We then use the Console.WriteLine command to print out myNumber
- Finally, we use Console.ReadLine to read that line
String Variables are wrapped in quotation marks; comment out the above code, highlight it all and press CTRL+K+C (to un-comment, CTRL+K+U). Next, type the following:
Dim name As String name = "Asim" Console.WriteLine(name) Console.ReadLine()
This should print out Asim. This code works the same as above, but this time it was a string data type. You can also add, subtract and perform other mathematical calculations. Under the above code, write the following:
Dim x As Integer Dim y As Integer x = 32 y = 15 Console.WriteLine(x + y) 'Add x (32) and y(15) ( 32 + 15 = ?) Console.ReadLine() ' ReadLine
You should get the value 47. This time we made two integer variables called x and y, assigned them a value, and then added them together.
Summary
- Variables start with the Dim keyword
- Variables can start with uppercase or lowercase characters