# Tutorial about Visual Basic programming language

- Link: https://www.teodoropiccinni.com/en/articles-en/tutorials-en/2019/08/tutorial-about-visual-basic-programming-language
- Published: 2019-08-25T19:26:39+00:00
- Author: Teodoro Piccinni

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](https://products.office.com/en-us/excel)
to test the written code.

Alternatively, you can use [Visual Studio Community](https://visualstudio.microsoft.com/en/vs/)
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](https://www.libreoffice.org/discover/calc/).
If you want to learn more, [write to me](https://www.teodoropiccinni.com/en/contacts).

### 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

![](https://www.teodoropiccinni.com/wp-content/uploads/2019/08/Excel_Customize_Ribbon.
jpg)

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

![](https://www.teodoropiccinni.com/wp-content/uploads/2019/08/Excel_developer_tab.
jpg)

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

![](https://www.teodoropiccinni.com/wp-content/uploads/2019/08/Excel_VB_editor-1024x550.
jpg)

## 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](https://www.teodoropiccinni.com/en/articles-en/tutorials-en/2019/08/tutorial-about-visual-basic-programming-language#esercizi).

### 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:

    ```wp-block-preformatted
    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](https://www.teodoropiccinni.com/en/articles-en/tutorials-en/2019/08/tutorial-about-visual-basic-programming-language#tipodato)
   we’re going to save into the variable. The complete list of variable types is
   available below: [data type](https://www.teodoropiccinni.com/wp-admin/post.php?action=edit&post=1115&ids=924#tipodato).

#### 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.

    ```wp-block-preformatted
    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](https://www.teodoropiccinni.com/en/articles-en/tutorials-en/2019/08/tutorial-about-visual-basic-programming-language#tipidato)
   we’re going to save into the variable. The complete list of variable types is
   available below: [data type](https://www.teodoropiccinni.com/wp-admin/post.php?action=edit&post=1115&ids=924#tipidato).
 *  **=** 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.

    ```wp-block-preformatted
    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](https://www.teodoropiccinni.com/wp-admin/post.php?action=edit&post=1115&ids=924#tipidato)
   we’re going to save into the variable. The complete list of variable types is
   available below: [data type](https://www.teodoropiccinni.com/wp-admin/post.php?action=edit&post=1115&ids=924#tipidato).

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.

    ```wp-block-preformatted
    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:

    ```wp-block-preformatted
    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:

    ```wp-block-preformatted
    Dim matrix(5, 5) As Double
    ```

#### Conditional selectors

    ```wp-block-preformatted
    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.

    ```wp-block-preformatted
    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.

    ```wp-block-preformatted
    Do
     ...
    While(condition)
    ```

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

    ```wp-block-preformatted
    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](https://www.teodoropiccinni.com/wp-admin/post.php?action=edit&post=1115&ids=924#tipidato).

### 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:

    ```wp-block-preformatted
    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.

![](https://www.teodoropiccinni.com/wp-content/uploads/2019/08/Excel_VB_editor_execute.
jpg)

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:

    ```wp-block-preformatted
    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:

    ```wp-block-preformatted
    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

| **Type** | **Data content** | **Required memory** | **Supported interval values** | 
| Byte | Integer numbers | 1 byte | From 0 to 255 | 
| Integer | Integer numbers | 2 | From -32768 to 32767  | 
| Long | Integer numbers | 4 | Around +/- 2 billions  | 
| Single | Decimal numbers in single-precision  | 4 | From +/- 1,401298e-45 to 3,402823e48  | 
| Double | Decimal numbers in double-precision  | 8 | From +/- 4,94065645841247e-324 to 1,79769313486232e308  | 
| String | Alphanumeric strings | 1 | From 0 to 255 characters | 
| Boolean | Logical values | 2 | 0 or 1 | 
| Date | Date and time | 8 | From 1/1/100 to 12/31/9999  | 
| Currency | Currency format numbers (4 decimals) | 8 | +/- 9e14 | 
| Variant | Generic Type | 8 | Any 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

 * [Official VBA manual from Microsoft website](https://docs.microsoft.com/en-us/office/vba/api/overview/)
 * [Wikipedia](https://en.wikipedia.org/wiki/Visual_Basic)
