Tutorial about Visual Basic programming language

During this course I will introduce Visual Basic version 6.0. Visual Basic is a programming language that I have repeatedly crossed in the past, but I had never studied its syntax before.

I will often shorten Visual Basic with VB.

Preamble

This is not a language that I consider useful for the career of a programmer, but I recognize its usefulness for educational purposes. Not by chance I found myself studying it, for the first time a few weeks ago, while I was helping a boy recover a school debt.

Being also the same language used to automate some Excel functions, knowing it allows us to understand the functioning of some spreadsheets often used by many companies loyal to the now deprecated Microsoft system.

Requirements

I take it for granted that those who follow the course have a smattering about the world of computer science, programming languages and the logic behind them.

  • Structured programming
  • Variables and variable types
  • Control structures (if, else, etc …)
  • Iterative structures (while, for, etc …)

Development environment

Let’s set our development environment. During the course I taught, I used Microsoft Excel to test the written code.

Alternatively, you can use Visual Studio Community edition, but setting up the project is a bit more complex.

As a final step, on my laptop running Linux, I was able to run the code with LibreOffice Calc. If you want to learn more, write to me.

Microsoft Excel

To write VB code, you must enable the Excel Developers tab.

The Development tab is not displayed by default, but you can add it to the ribbon.

  1. In the menu bar click on File
  2. Options
  3. Customize the ribbon
  4. In the Customize Ribbon window between the Main Tabs, select the Development box

The developer menu is presented in the following way for the latest versions of Excel.

Alternatively, right-click on the taskbar and select Customize the ribbon. From there, follow step 4 of the previous list.

Let’s learn the basics

Paragraphs below contain a summary of basic commands of the language. If you are impatient like me, and you want to see the language in action at first and then understand how it works, I suggest you to go directly to the exercises section.

Syntax

The syntax is the basis of language. Once we made sure that we know what a variable, a conditional or iterative structure are, we can see how these concepts are translated into Visual Basic.

Variables

The declaration of variables in Visual Basic must be carried out according to the following form:

Dim variableName as Type

Where:

  • Dim is a common part indicating that we are initializing a variable
  • variabileName is the name of the variable we are declaring
  • Type it’s the data type we’re going to save into the variable. The complete list of variable types is available below: data type.

Constant

Constants are a particular type of data that, once initialized, can never change its value during program execution. Precisely because of this feature I have to assign it a value in the declaration phase.

Public Const ConstantName as Type = value

Where:

  • Public indicates whether the scope of the variable can be Public or Private
  • Const indicates that I am initializing a constant
  • ConstantName is the name of the variable we are declaring
  • Type is the data type we’re going to save into the variable. The complete list of variable types is available below: data type.
  • = assignment of a value to the constant
  • value is the value to be assigned to the constant

Vectors

I will often use the word array and vector as synonyms, they are exactly the same thing. To declare a vector in Visual Basic, we need to define the size while creating the vector.

Dim speedSeries(n) as Type

Dove:

  • Dim is a common part indicating that we are initializing a variables
  • speedSeries is the name of the vector we are assigning
  • () indicate that this variable is a vector, a multidimensional variable
  • n indicates the size of the vector. During the declaration phase it is possible to choose whether the vector start from 0 or from 1 by writing (0 to n) or (1 to n)
  • Type is the data type we’re going to save into the variable. The complete list of variable types is available below: data type.

The arrays are created empty and can be populated later by iterating the between its values with a cycle. See the cycles in the next paragraph.

Public Const size as Integer = 3
Dim list(3) as Integer

For ind = 0 To size
     list(ind) = InputBox("Insert value " & ind & ":")
Next

or by calling up the individual memory areas of the array:

Public Const size as Integer = 3
Dim list(3) as Integer

list(0) = 10
list(1) = 20
list(2) = 50
list(3) = 5

Matrix

The matrices are nothing more than arrays of arrays and declare themselves as follows:

Dim matrix(5, 5) As Double

Conditional selectors

If (condition) Then
 ...
ElseIf (condition 2) Then
 ...
Else
 ...
End If

Iterative loops

The While loop is a type of iterative structure that verifies the condition before entering the cycle. If the condition is true it executes the cycle until this condition becomes false.

While (condition)
 ...
End While

The Do … While serves in cases where we want to execute the cycle even when the condition of the While is not satisfied before entering the cycle.

Do
 ...
While(condition)

The For loop is always executed, contrary to what happened with the While loop.

For index=0 To limit
 ...
Next

The For cycle is composed of two main elements:

  • index has the function of counter. It tells the cycle from which number to start counting and is incremented at each iteration (by the Next command)
  • limit tells the For loop when to stop

Both variables must be declared as Integer type.

Objects

Objects are elements of the interface of a Visual Basic program. Among the objects I remember the buttons, select boxes, text boxes, etc …

Each object is characterized by three two components:

  • Property
    • They characterize the object
    • Example: in color, size, name, etc …
  • Events
    • Referred to a particular object
    • When an event occurs, they execute the portion of code present within the event
    • Example: Click, Change, etc …

We don’t go into the details of these components, you can fiddle with your development environment after learning the basics of the VB.

The main objects we will use are:

  • MsgBox
  • InputBox
  • TextBox
  • Label
  • CommandButton

Exercises

After this tedious explanation of the various components of the language, we begin to write some code.

Hello World

Our first program will do nothing but display a small window with “Hello World!” That’s how:

  1. Open Excel
  2. Select the Developers tab
  3. Select Visual Basic
  4. Once in the VB editor, in the left area you will have a tree structure of the contents of the current file. Click them with the right mouse button and select Insert and then UserForm
  5. A small empty window and a bar with the icons of the available objects will appear. Click on Button and drag it to the newly created UserForm1 window
  6. Double-click on the button just created, you will be sent to view the application’s source code. Write them in the following code:
Private Sub CommandButton1_Click()
     MsgBox ("Hello World!")
End Sub

To check the operation, click on the Execute button at the top of the function bar. The icon is a small green “play” key.

Amused? Go on!

Hello Teodoro!

To complicate our lives, let’s add a Label, a TextBox and some variables.

  1. Starting from our empty form (see the previous exercise if you don’t remember how to do it)
  2. Insert a Label, in which we will write “Enter your name:”
  3. Insert a TextBox
  4. Insert a Button
  5. Double click on the button and in the code view you have to write the following:
Dim name As String

Private Sub CommandButton1_Click()
     name = TextBox1.Text 
     MsgBox ("Hello " & name & "'s World!")
End Sub

Click on the Execute button. We should see our little program that will ask us to enter our name. Write Teodoro and press on the CommandButton1.

If everything works you will have to see a small window with “Hello Teodoro’s World!”

Ok, we’ve done the easiest parts are done.

Add everything!

We then add an Array, a constant, a loop, some InputBoxes and the possibility of going to modify the contents of a TextBox.

  1. Starting from our empty form (see the first exercise if you don’t remember how to do it)
  2. Insert a Label, in which we will write “Here is your array”
  3. Insert a TextBox immediately below (enable the multi line option if you want to display the content on multiple lines.
  4. Insert three Buttons
  5. Double click on the button and in the code view we write the following:
  1. sd
  2. Partendo sempre dal nostro form vuoto (vedi il primo esercizio se non ti ricordi come fare)
  3. Inseriamo una Label, dentro la quale scriveremo “Ecco il tuo array”
  4. Inseriamo una TextBox subito sotto (abilita l’opzione multi linea se vuoi visualizzare il contenuto su più linee.
  5. Inseriamo tre Bottoni
  6. Facciamo doppio click sul bottone e nella visualizzazione del codice scriviamo quanto segue:
Private Const size As Integer = 3
Dim ind As Integer
Dim testoArray As String
Dim list(size) As String

Private Sub CommandButton1_Click()
     testoArray = "Array name: list" & vbCrLf & "Array content:"
     If list(0) = "" Then
          list(0) = "10"
          list(1) = "20"
          list(2) = "50"
          list(3) = "5"
     End If 

     For ind = 0 To size
          testoArray = testoArray & vbCrLf & list(ind)
     Next

     TextBox2.Text = testoArray
End Sub

Private Sub CommandButton2_Click()
     For ind = 0 To size
          list(ind) = InputBox("Insert value " & ind & ":")
     Next
End Sub

Private Sub CommandButton3_Click()
     End
End Sub

Appendix

Data types

TypeData contentRequired memorySupported interval values
ByteInteger numbers1 byteFrom 0 to 255
IntegerInteger numbers2From -32768 to 32767
LongInteger numbers4Around +/- 2 billions
SingleDecimal numbers in single-precision 4From +/- 1,401298e-45 to 3,402823e48
DoubleDecimal numbers in double-precision 8From +/- 4,94065645841247e-324 to 1,79769313486232e308
StringAlphanumeric strings1From 0 to 255 characters
BooleanLogical values20 or 1
DateDate and time8From 1/1/100 to 12/31/9999
CurrencyCurrency format numbers (4 decimals)8+/- 9e14
VariantGeneric Type8Any of the previous Types

Other

There is the possibility of writing texts on multiple lines: vbCrLf prints a newline character and sends the text to a new line.

Links