Many computer languages share a core set of features. Sometimes they are very similar in different languages, sometimes radically different. Some features regarded by users of one language as indispensable may be completely missing from other perfectly usable languages.

Statements

edit

A statement in Visual Basic is like a command given to the computer. Functions and subroutines are made out of statements.

A statement generally consists of the name of a subroutine followed by a list of arguments:

Debug.Print "Hello World"

The first word (Debug) is the name of a built in object in Visual Basic. the second word (Print) is the name of a method of that object. "Hello World" is the argument to the method. The result is:

 Hello World

printed to the Immediate Window.

In Visual Basic Classic subroutine call statements can be written in two ways:

  x "Hello", "World"
  Call x("Hello", "World")

x is a subroutine which takes two string arguments. The keyword Call is a leftover from older versions of Basic. If you use this form you must enclose the entire argument list in a parenthesis. Sometimes the programmer wants to call a function but is not interested in the return value only in the side-effects. In such cases he or she will call the function as though it were a subroutine, however only the first form above can be used.

There are other more complex statements which can span several lines of code:

  • If..Else..End If
  • Do While..Loop

These compound statements include other statements and expressions.

Variables

edit

Like most programming languages, Visual Basic is able to use and process named variables and their contents. Variables are most simply described as names by which we refer to some location in memory - a location that holds a value with which we are working.

It often helps to think of variables as a 'pigeonhole', or a placeholder for a value. You can think of a variable as being equivalent to its value. So, if you have a variable i that is initialized to 4, i+1 will equal 5.

In Visual Basic variables can be declared before using them or the programmer can let the compiler allocate space for them. For any but the simplest programs it is better to declare all variables. This has several benefits:

  • you get the datatype you want instead of Variant,
  • the compiler can sometimes check that you have used the correct type.

All variables in Visual Basic are typed, even those declared as Variant. If you don't specify the type then the compiler will use Variant. A Variant variable is one that can hold data of any type.

Declaration of Variables

edit

Here is an example of declaring an integer, which we've called some_number.

 Dim some_number As Integer

You can also declare multiple variables with one statement:

Dim anumber, anothernumber, yetanothernumber As Integer

This is not a good idea because it is too easy to forget that in Visual Basic the type name applies only to the immediately preceding variable name. The example declares two Variants and one Integer

You can demonstrate what actually happens by this little program:

  Option Explicit
  
  Public Sub main()
    
    Dim anumber, anothernumber, yetanothernumber As Integer
    Dim v As Variant
    
    Debug.Print TypeName(anumber), VarType(anumber), _
         TypeName(anothernumber), VarType(anothernumber), _
         TypeName(yetanothernumber), VarType(yetanothernumber)
    
    Debug.Print TypeName(anumber), VarType(v)
    
    Debug.Print "Assign a number to anumber"
    anumber = 1
    Debug.Print TypeName(anumber), VarType(anumber)
    
    Debug.Print "Assign a string to anumber"
    anumber = "a string"
    Debug.Print TypeName(anumber), VarType(anumber)
    
  End Sub

The result is:

 Empty          0            Empty          0            Integer        2 
 Empty          0 
 Assign a number to anumber
 Integer        2 
 Assign a string to anumber
 String         8

Notice that both VarType and TypeName return information about the variable stored inside the Variant not the Variant itself.

To declare three integers in succession then, use:

Dim anumber As Integer, anothernumber As Integer, yetanothernumber As Integer

In Visual Basic it is not possible to combine declaration and initialization with variables (as VB does not support constructors - see Objects and Initialise though), the following statement is illegal:

Dim some_number As Integer = 3

Only constant declarations allow you to do this:

Const some_number As Integer = 3

In Visual Basic variables may be declared anywhere inside a subroutine, function or property, where their scope is restricted to that routine. They may also be declared in the declarations section of a module before any subroutines, functions or properties, where they have module level scope.

By default, variables do not have to be declared before use. Any variables created this way, will be of Variant type. This behaviour can be overrriden by using the Option Explicit statement at the top of a module and will force the programmer to declare all variables before use.

After declaring variables, you can assign a value to a variable later on using a statement like this:

Let some_number = 3

The use of the Let keyword is optional, so:

some_number = 3

is also a valid statement.

You can also assign a variable the value of another variable, like so:

anumber = anothernumber

In Visual Basic you cannot assign multiple variables the same value with one statement. the following statement does not do what a C programmer would expect:

anumber = anothernumber = yetanothernumber = 3

Instead it treats all but the first = signs as equality test operators and then assigns either True or False to anumber depending on the values of anothernumber and yetanotherniumber.

Naming Variables

edit

Variable names in Visual Basic are made up of letters (upper and lower case) and digits. The underscore character, "_", is also permitted. Names must not begin with a digit. Names can be as long as you like.

Some examples of valid (but not very descriptive) Visual Basic variable names:

 foo
 Bar
 BAZ
 foo_bar
 a_foo42_
 QuUx

Some examples of invalid Visual Basic variable names:

2foo
must not begin with a digit
my foo
spaces not allowed in names
$foo
$ not allowed -- only letters, digits, and _
while
language keywords cannot be used as names
_xxx
leading underscore not allowed.

Certain words are reserved as keywords in the language, and these cannot be used as variable names, or indeed as names of anything else.

In addition there are certain sets of names that, while not language keywords, are reserved for one reason or another.

The naming rules for variables also apply to other language constructs such as function names and module names.

It is good practice to get into the habit of using descriptive variable names. If you look at a section of code many months after you created it and see the variables var1, var2 etc., you will more than likely have no idea what they control. Variable names such as textinput or time_start are much more descriptive - you know exactly what they do. If you have a variable name comprised of more than one word, it is convention to begin the next word with a capital letter. Remember you can't use spaces in variable names, and sensible capital use makes it easier to distinguish between the words. When typing the variable name later in the code, you can type all in lowercase - once you leave the line in question, if the variable name is valid VB will capitalize it as appropriate.

Literals

edit

Anytime within a program in which you specify a value explicitly instead of referring to a variable or some other form of data, that value is referred to as a literal. In the initialization example above, 3 is a literal. Numbers can be written as whole numbers, decimal fractions, 'scientific' notation or hex. To identify a hex number, simply prefix the number with &H.

Conditions

edit

Conditional clauses are blocks of code that will only execute if a particular expression (the condition) is true.

If Statements

edit

If statements are the most flexible conditional statements: see Branching

Select Case

edit

Often it is necessary to compare one specific variable against several values. For this kind of conditional expression the Select Case statement is used.

Unconditionals

edit

Unconditionals let you change the flow of your program without a condition. These are the Exit, End and Goto statements.

Loops

edit

Loops allow you to have a set of statements repeated over and over again.

To repeat a given piece of code a set number of times or for every element in a list: see For..Next Loops


Previous: Case Studies Contents Next: Coding Standards