Sie sind auf Seite 1von 10

Visual Basic

Visual Basic has a very simple programming syntax. The language is not case-sensitive and it is
designed for people new to the programming world, making it a good place to start.
Go ahead and start a new VB Console Application and give it the name Syntax. You should see
the following code:
Module Module1
Sub Main()
End Sub
End Module

Your code goes between the Sub Main() and End Sub. In VB, lines does not end with a semicolon; compared to C# and most other languages, VB is kept simple!

Comments

Single line comments start with an apostrophe (')


There are no block comments in VB
XML comments start with three apostrophes; these are useful for documentation purposes

Organizing Code
Organizing code is very important, and comments and regions are very useful. It is considered
good practice to group and comment your code so it is easy for other developers to work on it.
Comments should provide a small description of that piece of code, and regions are useful use to
group code together. To create a region you use the following syntax:
#region "region name"
Other code here..
#End Region

This will be demonstrated further in later tutorials.

Write Your First Program


Now it is time to write your first program. Between the Sub Main() and End Sub enter the
following:
Console.WriteLine("My First Visual Basic Program!")

Console.ReadLine()

Hit F5, and you should see the following print out:
My First Visual Basic Program!
Console.WriteLine is a system method.
the period (or dot) is called Member Accessor

Files
When you build your program, certain files are created. It may seem excessive, but they are
actually just simple files and instructions for your program and the Visual Studio IDE. Navigate
to C:\users\<yourname>\ Documents\Visual Studio\Syntax (or the saved file location). Find
the file called Syntax.sln and a folder called Syntax. If you open the Syntax.sln (sln is a Visual
Studio Solution file) with notepad, you will see it has some global settings; we advise you not
edit anything!
In the Syntax folder there will be 3 folders: obj, My Project and bin. There will also be two
files: Module1.vb and Syntax.vbproj. The Module1.vb is our source code for our program.
Next, open up Syntax.vbproj, which is a Visual Basic Project File. This is actually an XML file
which stores information about other file locations; do NOT edit it.
Now open up the bin folder; inside is another folder called debug which is where your program
will output. If you double click Syntax.exe the program will run. Go back and open up the My
Project folder, and focus on the file called AssemblyInfo.vb. This stores information about the
program such as author, copyright, trademark, etc.

Summary
Visual Basic has a very simple programming syntax. Most of the code is easily understandable,
even if you are not familiar with programming. The language is not case-sensitive, inline
comments start with an apostrophe, and XML comments start with 3 apostrophes
Visual Studio 2012 IDE Visual Basic Variables
Visual Basic Tutorial

Basics
Visual Basic Tutorial
Visual Basic Installation
Visual Studio 2012 IDE
General
Visual Basic Syntax

Visual Basic Variables


Visual Basic Strings
Visual Basic Dates And Times
Visual Basic Math
Visual Basic Operators
Decision Statements
Visual Basic If Statement
Visual Basic Select Case
Loops
Visual Basic For Next
Visual Basic While Statement
Visual Basic Do Loops
Advanced
Visual Basic Arrays
Visual Basic Methods
Visual Basic Methods (Continued, Optional Parameters and Overloading)
Visual Basic Managing Errors
Visual Basic Creating and Managing Classes
Real Life Applications
Visual Basic Text Editor
Visual Basic - Slideshow

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
Numbers with decimals e.g. 5.2
Point
Boolean
True Or False
Floating Point numbers but more
Double
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

Visual Basic Syntax Visual Basic Strings

Visual Basic Tutorial

Basics
Visual Basic Tutorial
Visual Basic Installation
Visual Studio 2012 IDE
General
Visual Basic Syntax
Visual Basic Variables
Visual Basic Strings
Visual Basic Dates And Times
Visual Basic Math
Visual Basic Operators
Decision Statements
Visual Basic If Statement
Visual Basic Select Case
Loops
Visual Basic For Next
Visual Basic While Statement
Visual Basic Do Loops
Advanced
Visual Basic Arrays
Visual Basic Methods
Visual Basic Methods (Continued, Optional Parameters and Overloading)
Visual Basic Managing Errors
Visual Basic Creating and Managing Classes
Real Life Applications
Visual Basic Text Editor
Visual Basic - Slideshow

Visual Basic Strings

Strings are enclosed in double quotes ( " " )


Strings are a data type
Strings are a collection of characters

Syntax

Dim stringName As String

Example

Here are several ways in which you can manipulate strings. Create a new VB Console
Application and name it Strings. Next, type the following:
Sub Main()
Dim myName As String
myName = "thecodingguys"
Console.WriteLine(myName)
Console.ReadLine()
End Sub

Press F5 to debug and you should see the text thecodingguys. This is a simple string. Comment
out the above code (CTRL+K+C).

Escape Character
In cases where you need to escape quotation marks which get in the way, see the following
example:
Dim text As String
text = "Asim Said: "Hello World" "
Console.WriteLine(text)
Console.ReadLine()

If you run this (F5), you will get an error saying End of Statement Expected. The problem is
that VB thinks that the line ends at "Asim Said:", which is incorrect. So what we need to do is
put four double quotes around Hello World, as such:
Dim text As String
text = "Asim Said: ""Hello World"" "
Console.WriteLine(text)
Console.ReadLine()

Output
Asim Said: "Hello World"

New Line
When you need a new line, in C# the new line is simply \n; however in VB it is quite different.
Comment out the above code and put this below:

Dim newLine As String


newLine = "This is a new" & vbCrLf & "Line"
Console.WriteLine(newLine)
Console.ReadLine()

This time we use the keyword vbCrLf to make a new line. Put your first line code in one
quotation then your second in another, and in between put & vbCrLf &

Concatenation
Concatenation means joining two things together, in this case joining strings. It can be very
useful when you want to link something together to form a sentence. You use the & ( or + ) to
form a concatenation. For example:
Console.WriteLine(myName & " is awesome")

This will print out "thecodingguys is awesome". myName is a variable we created earlier.

String.Format
The string.format method is useful for formatting your text, and you can format it in many ways.
For example, say you wrote Console.WriteLine ("Your balance is 5"); however, if you gave
this away to someone in the USA or Italy, they would see the British pound symbol instead
of their own country's currency symbol. This is where the .Net Framework becomes useful, as it
can detect the user's country / regional settings and format the piece of text to match
those settings.
Example
Dim myNumber As Double = 158
strFormat = String.Format("{0:C}", myNumber)
Console.WriteLine(strFormat)
Console.ReadLine()

Now when you debug this (F5) you should see it print out 158 with your country's currency
symbol in front of it. For more ways to format strings, see the table below:
Form
at

Description

{0:C}

Currency
Symbol

{0:P}

Percentage
Symbol

{0:N}

Thousand Separ
ator

The 0 in the format key specifies the parameter you want to format, followed by a colon and then
the formatting type.
Example 2

This time we use two parameters.


Dim myNumber As Double = 158
Dim mySecondNumber As Integer = 25
strFormat = String.Format("{0:C} {1:P}", myNumber, mySecondNumber)
Console.WriteLine(strFormat)
Console.ReadLine()

In this example, the first parameter (myNumber) would appear as 158 and the second one
would appear as 25%.

Manipulating Strings
There are many built-in methods available to you, so you can format strings in a number of
ways. For example, you can format a string and make it all uppercase, you can remove spaces, or
you can simply count the length of the string. In the next few examples, you will see a few useful
methods used to manipulate strings.
In the following examples we will be working with a string called yourMessage which will have
the text Welcome to thecodingguys, and another string finalResult which is set to nothing.
Dim yourMessage As String = "Welcome to thecodingguys"
Dim finalResult As String = Nothing

For the sake of brevity we have omitted the Console.WritelIne(finalResult), from the examples;
however if you want to add it, remember to add the Console.ReadLine() as well.

ToUpper and ToLower


The ToUpper and ToLower converts a string either to uppercase or lowercase format.
Example

finalResult = yourMessage.ToUpper()
finalResult = yourMessage.ToLower()

Replace
The replace method replaces a string with another string. It takes two parameters, the old string
and new string, and it can also take chars. In the following example, the spaces in yourMessage
are removed and replaced with dashes.

finalResult = yourMessage.Replace(" ", "-")

Output
Welcome-to-thecodingguys

Substring
The substring method can be used to return parts of a string. For example, from the yourMessage
string we can return the first 5 characters only. The substing method takes two parameters: the
start index and length index as integer.
Example

finalResult = yourMessage.Substring(0, 7)

The 0 specifies the start point, in this case it is at the beginning; the 7 specifies how many
characters we want from the starting point. To get all the characters you would do as follows:
finalResult = yourMessage.Substring(0, yourMessage.Length)

Output
Welcome

Exceptions: Watch out for the ArguementOutofRangeException, which is common. This


occurs when the string length is shorter than the points specified; for example if 0,
25 was used, it would give that exception as yourMessage is only 24 characters
long.

Count
The count and length method return the length of the string.
finalResult = yourMessage.Count()

There are many more methods available.


Method
Contains

Description
See if a string contains a
certain piece of text

Output
Reutrns boolean (either true
of false)

StartsWi See if a string starts with a certain


th
piece of text

Boolean - true of false

EndsWit See if a string ends with a certain


h
piece of text

Boolean - true of false.

Summary

In this tutorial we showed you how to format and manipulate strings in Visual Basic.

New Line is vbCrLF


Escape Character ""
String.Format followed by {0:C} or N or P. (The String.Format Full List is
available at MSDN Library VB String Formats)
Functions: ToUpper, ToLower, Replace, Substring, etc.

Visual Basic Variables Visual Basic Dates And Times

Visual Basic Tutorial

Basics
Visual Basic Tutorial
Visual Basic Installation
Visual Studio 2012 IDE
General
Visual Basic Syntax
Visual Basic Variables
Visual Basic Strings
Visual Basic Dates And Times
Visual Basic Math
Visual Basic Operators
Decision Statements
Visual Basic If Statement
Visual Basic Select Case
Loops
Visual Basic For Next
Visual Basic While Statement
Visual Basic Do Loops
Advanced
Visual Basic Arrays
Visual Basic Methods
Visual Basic Methods (Continued, Optional Parameters and Overloading)
Visual Basic Managing Errors
Visual Basic Creating and Managing Classes
Real Life Applications
Visual Basic Text Editor
Visual Basic - Slideshow