Fundamentals of Visual Basic

Introduction

Microsoft Visual Basic is a programming language that can be used to create various types of computer applications, also called apps, also called computer programs, or just programs. The popularity of Visual Basic came from the "visual" aspect in its name. This consists of creating beautiful graphical applications by selecting objects, named Windows controls, and adding them to another object, a form. This approach makes application developement intuitive and fast. Of course, code is also necessary to control the behavior of the intended finished product. Behind-the-ceines, Microsoft Visual Basic is a full-blown computer language with many attractive feaures that you should be aware of before deciding to create graphical applications from it.

In our lessons, we are going to study the language that serves as a foundation to Visual Basic.

Introduction to Projects

The primary job of an application is to show its results on the computer monitor, and there are various types of applications. A console application is a program that displays its results in a black window referred to as a DOS window. In some of our lessons, we will create those types of applications. The Visual Basic language provides a rectangular object called a message box. If you create a Visual Basic application, you can display the results in a message box. That's what we will use in most of our lessons.

To create an application, you start with a project. There are two main ways you can create a Visual Basic project. You can use a text editor such as Notepad. In this case, to create a program, you write the necessary instructions in a text-based document. This is called a source file. A source file that contains Visual Basic instructions is a regular, simple, ASCII, text-based file. It has the extension .vb as a Windows file. After creating and saving the file, you must compile and execute it at the Command Prompt.

A better and fast way to create an application is to use a programming environment. In this case, you can use Microsoft Visual Studio. It is freely available from the Microsoft website. Simply do a search on "visual studio". Find the webpage and link to Microsoft Visual Studio Community Edition, download, and install it to your computer. For most of our lessons, we will use Microsoft Visual Studio to study the Visual Basic language.

Introduction to Modules

In a Visual Basic document, you write code as we will learn throughout our lessons. The code that is conform to the Visual Basic language is included in a section known as the module. This section starts with the Module keyword followed by a name and ends with the End Module expression. Based on this, a simple file in Visual Basic would have the following:

Module module-name

End Module

Start with the keyword Module and a space. Add a name. The name must follow some rules we will review. Move to the next line(s) and write the code you judge necessary. On the last line, type the expression End Module.

Introduction to Procedures

A procedure is a section of code that takes care of a specific task. A procedure can be created in a module. In a module, the basic formula of a procedure is:

Sub procedure-name()

End Sub

Start with the Sub keyword followed by a space. Add a name. The name of a procedure must be followed by parentheses. At a minimum, you can leave the parentheses empty. Write your code in the next line(s). On the last line of the procedure, type End Sub. Because a module holds the code of a Visual Basic program, a procedure is included inside the start and the end of the module section. This would be done as follows:

Module module-name
      
    Sub procedure-name()

    End Sub

End Module

We will come back to procedures in another lesson. For now, the most fundamental procedure used in Visual Basic is called Main. In a program, the Main() procedure is the entry point. That is where the program starts.

Another common procedure highly used in Visual Basic is called MsgBox. As its name indicates, the MsgBox() procedure is used to display a message in a dialog box. To make this happen, you can include the message inside the parentheses of MsgBox. The message itself should be included in double-quotes. An example would be:

MsgBox("Whatever")

The MsgBox() procedure provides more details. We will come back to it in future lessons.

Practical LearningPractical Learning: Starting a Visual Basic Project

  1. Start Microsoft Visual Studio
  2. In the Visual Studio 2022 dialog box, under Get Started, click Create a New Project

    Create a New Project

  3. In the Create a New Project dialog box, click All Languages
  4. In the menu that comes up, click Visual Basic

    New Project

  5. In the large list on the right side of the dialog box, and click Console App (it should be selected already)

    New Project

  6. Click Next
  7. Change the Name to Exercise1
    Accept or change the Location

    New Project

  8. Make sure the Framework combo box is displaying .NET 6.0 (Long-Term Support)

    New Project

    If it is not, click the arrow of the Framework combo box and select .NET 6.0 (Long-Term Support)
  9. Click Create

Practical LearningPractical Learning: Introducing Modules

  1. In the empty document, type the following:
    Module Exercise
    
    End Module
    Notepad
  2. On the main menu, click File -> Save

Practical LearningPractical Learning: Introducing Procedures

  1. Change the document as follows:
    Module Exercise
        Sub Main()
    	MsgBox("Welcome to the Wonderful World of Visual Basic.")
        End Sub
    End Module
  2. On the main menu, click File -> Save

Building a Program

As mentioned already, you write the instructions of your project in English. But the computer doesn't understant it. The instructions must be translated in a language the computer can understand. That language is called machine language. To translate the instructions from English to machine dialect, you use a program named a compiler. In reality, a compiler is a group of sub-programs that accomplish various goals to get a functional program at the end. The end result is a program that can be executed in a computer other than the one you used to create the project. That final program is called an executable.

Ae mentioned already, a compiler is a computer program made of internal other sub-programs. One of the sub-programs, in fact probably the first, of a compiler is called a parser. A parser "scans" a file that contains (part of) the program. It checks the syntax, keywords, unknown words, and some other routines. If the parser finds a problem, which could be anything, either it stops or it continues making a list of the mistakes it found. Then it displays this list to you to fix. Sometimes it would point to the exact line where the/a problem was found. Sometimes it would point to the line where the problem showed its impact although the problem may be found somewhere else. With experience, you will know how to fix the programs or troubleshoot the problems.

If the parser doesn't find any problem, or after you have fixed the problems, it (the parser) passes its result(s) to the compiler. The compiler calls another program called a linker. If the program contains just one file, the linker considers it. If the program contains more than one file, the linker considers them. The linker gathers some of the files that the compiler shipped with (those files that your program needs in order to work), puts them together ("links" them) with your file(s) to get your instructions in a manner that can produce a suitable result. If there is no significant problem, the compiler creates the executable. This doesn't mean that everything is alright, it only means that the compiler thinks that everything is alright: it is still possible that the result may not be what you would expect. We will come back to these issues.

To make your life easier, all of the sub-programs (parser, linker, debugger, etc) that ship with Visual Basic are grouped in one large program: the compiler. Therefore, from now on, we will use the word "compiler" to refer to the program you use to translate your English instructions into a machine language.

Microsoft created and makes freely available a Visual Basic compiler you can use to create your applications. The Visual Basic compiler is named vbc. A compiler is primarily a computer program, that is an executable. As such, it uses to extension .exe. Therefore, the compiler we will use to create our program is called vbc.exe.

As mentioned already, the vbc.exe compiler is freely available. You can get it by downloading the .NET Framework from the Microsoft web site. Normally, you are likely to have the .NET Framework installed in your computer already. By default, it is installed in C:\Windows\Microsoft.NET\Framework\v4.0.21006.

You can use the vbc.exe to create programs from the Command Prompt. To do this, you can add the compiler's path to the Path of the Environment Variables. To start, use a file utility such as Windows Explorer and display the folder where vbc.exe is installed. Here is its path in Windows Explorer:

The vbc Compiler

Select the path in the top combo box and copy it to the clipboard. Start the Control Panel. Click System and Security:

System

In the System and Security section, click System:

System

In the System window, click Change Settings. In the System Properties dialog box, click the Advanced tab. Click the Environment Variables button:

System Properties

In the System Variables section, double-click Path or click it and click Edit:

Environment Variables

Press the End key, type a semi-colon ";". Paste the value you had copied from the clipboard:

Path

Click OK three times.

Open the Command Prompt. Type CD\ and press Enter to move to the root drive. Type CD and a space, followed by the folder (and sub-folder(s)) where the file is located, and press Enter. To compile, type vbc followed by the name of the file and its extension:

Compiling from th Command Prompt

The file produced from this operation has the extension .exe. By default, it holds same name as the file you had used. If you want to get an executable using a name of your choice, after vbc, type /out: followed by the name you want, followed by a .exe extension, followed by a space, and followed by the name of the file you had created, with its extension. The formula to follow would be:

vbc /out:NameOfExecutate.exe Filename.vb

The NameOfExecutate represents the name you want the executable to have. If the name you want is in one word, you can just type it. Here is an example:

vbc /out:Welcome.exe Exercise.vb

Compiling from th Command Prompt

If you want a name made of various words, you can include those words in double-quotes.

If you are creating your application using a text editor and if you create many files, when compiling the project, you must remember to reference each file. To do that, in the last section, add the name of each file with its extension:

vbc FileName1.vb FileName2.vb FileName_n.vb

The executable you get is the one you can use on other computers and that you can distribute to other people.

Executing a Program

After building the code, you and your users can execute it. If you are working from the Command Prompt, to execute the project, type the name of the file that has the .exe extension and press Enter:

Compiling from th Command Prompt

If you are working from Microsoft Visual C# 2010 Express or from Microsoft Visual Studio, to execute an application, on the main menu, you can click Debug -> Start Debugging.

 

A Solution and its Projects

 

Creating a Project

Although you can creat a complete and fully functional application using a text editor, Microsoft Visual Studio and Microsoft Visual Basic 2010 Express provide a graphical environment that is more convenient. You start by creating a project. To create a project:

  • On the main menu, click File -> New Project...
  • On the Start Page, click New Project...
  • Press Ctrl + N

Creating a Solution

When you start a new application from the New Project dialog box, you are asked whether you want to create a new solution too, and you must give it a name. By default, the new project and solution would hold the same name. If you accept the suggestions, you would get a main folder with the name of the project. Inside of that folder, there would be a folder with the same name. That inside folder would represent the project.

After creating a solution, its name appears on the title bar of Microsoft Visual Studio. The name of the project would appear in the Solution Explorer.

Practical Learning: Introducing the Visual Basic Language

  1. Launch either Microsoft Visual Studio or Microsoft Visual Basic 2010 Express
  2. On the main menu, click File -> New Project...
  3. If you are using Microsoft Visual Studio, in the left list, expand Visual Basic and click Windows. In the right list, click Empty Project. Change the Name to GeneralCensus before clicking OK
     
    New Project
    If you are using Microsoft Visual Basic 2010 Express, in the middle list, click Console Application. Change the Name to GeneralCensus
    New Project
    Click OK

Introduction to Managing Solutions and Projects

 

The Solution Explorer

The Solution Explorer is a window that displays a list of the files that make up a project. To access the Solution Explorer:

  • If the Solution Explorer is not yet showing on the screen:
    • On the main menu, click View -> Solution Explorer
    • On the Standard toolbar, click the Solution Explorer button Solution Explorer
  • If the Solution Explorer is already showing, click its tab

The Solution Explorer is made of four sections. Like every regular window, the Solution Explorer is equipped with a title bar that displays its name on the left side and three buttons on the right side:

  • The Window Position button Window Position displays a menu when you click it:
     
    Window Position
     
    The Float option is enabled if the window is docked to a side of the screen. The Float option is disabled if the window is already floating. If the window is docked and you click Float, it would be moved from its docked position and would float. As an alternative to float a docked window, drag its title bar away from its docked position:
     
    Floating Window

    To dock a floating  window, drag its title bar

Under its title bar, the second section of the Solution Explorer is a toolbar:Toolbar:

  • The Properties button allows you to display the Properties window
  • The Show All Files button is used to show the hidden files of the project
  •  As its name indicates, the Refresh button is used to refresh the list of files and resources of the project
  • The View Code button is used to show the code of a class

The third part of the Solution Explorer is its body. It shows the folders, files, and resources that are part of the current project. To expand a node, you can either click its button or double-click its name. To collapse a node, either click its button or double-click it.

The root of the list is the name of the solution. Under the root is the name of the current project. If the solution contains more than one project, the name of each project is represented under the solution. Inside of the project are its folders, files, and resources. The first item under a project name is References. After the References node, there are the names of the classes that are part of the project.

The fourth part of the Solution Explorer is its tab.

The Properties Window

The Properties window shows the Windows operating system's details of the files or resources used in a project. To display it:

  • If the Properties window is not yet displaying
    • Oon the main menu, click View -> Properties window
    • On the Standard toolbar, click the Properties button Properties
  • If the Properties window is displaying already, click its tab

The display and rectangular behavior of the Properties window follows the description we had for the Solution Explorer.

To show the operating system's characteristics of a project or a file, in the Solution Explorer, click the object:

  • If you click a solution, the Properties window would show its name and its location
  • If you click a project, the Properties window would show its project file
  • If you click a file, the Properties window would show its name (in the File Name field) and its location (in the Full Path) field

The Properties window displays different fields depending on the item selected in the Solution Explorer. You can change some things in the Properties window. When a field is disabled, it means you cannot modify it.

Managing a Solution

 

Introduction

A solution is used to coordinate the different aspects of an application that is being created. When you have created a project, the name of the solution displays as the top node of the tree in the Solution Explorer:

Solution Explorer

The title bar of the studio displays the name of the solution in the left section:

Solution

If you start saving a project for the first time, it would bring the Save Project dialog box. By default, Microsoft Visual Studio selects your personal directory as the path to the solution. This is called the location. In the location, Microsoft Visual Studio creates a folder as the solution of the project. The solution must have, or must be stored, in its own folder. As mentioned earlier, Microsoft Visual Studio uses the name of the project as the name of the solution. To rename the solution, you can change the string in the Solution Name text box. Remember that you can enter the name of the project in the Name text box. Here is an example:

Save Project

When you save a project (for the first time), by default, Microsoft Visual Studio creates a new folder for it in the Documents\Visual Studio 2010\Projects folder. It uses the name of the solution to name the folder. It creates some files and stores them in that new folder. Then, it creates a sub-folder, using the name of the project, inside of the folder of the solution. Besides the sub-folder with the name as the project, it creates another folder named debug. It also creates another folder named Debug in the sub-folder of the name of the project. In each folder and some other folders, it creates some files that we will not pay attention to for now.

If the project had already been saved but you want to change the name of the solution, on the main menu, you can click File -> Save solution-name.sln As... This would bring the Save File As dialog box where you can specify the name of the solution and click Save.

Renaming a Solution

If you don't like the name of a solution, to rename it, in the Solution Explorer, right-click it and click Rename:

Renaming a Solution

As an alternative, in the Solution Explorer, click the name of the project, in the Properties window, click the value of the (Name) field, then edit it or type a new one:

Renaming a Solution

Deleting a Solution

Deleting a Solution is equivalent to deleting a file. To delete a solution, use a file utility such as Windows Explorer, locate the folder that contains the solution, and delete it.

Managing a Project

 

Saving a Project 

If you are creating your application using a text editor, you must save your file(s) in a folder you will create. When Microsoft Visual Studio 2010 (any edition) is installed, it creates a folder named Visual Studio 2010 in your Documents folder. The Documents folder is called your personal drive or your personal directory. Inside of the Visual Studio 2010 folder, it creates a sub-folder named Projects. By default, this is where it would save your projects, each with its own folder.

To save a project, on the Standard toolbar, you can click the Save All button Save All. Alternatively, on the main menu, you can click File -> Save All. If the project had already been saved but you want to save it under a different name, on the main menu, you can click File -> Save project name As...

Opening a Project 

There are a various ways you can open an existing project:

  • On the main menu, click File -> Open Project...
  • On the Start Page, click Open Project...
  • Press Ctrl + Shift + O

Adding a Project

A solution in Microsoft Visual Studio can contain one or more projects. That is, after creating the first project, you can add another project to the same solution and you can add as many projects as you want.

To add a new project to a solution (in Microsoft Visual Studio):

  • On the main menu, click File -> Add -> New Project...
  • In the Solution Explorer, right-click the name of the solution, position the mouse on Add, and click New Project...

This would display the Add New Project dialog box. In the Templates list, select the type of project you want. Accept or change the name of the project, then click OK.

The names of the different projects are listed in the Solution Explorer.

Renaming a Project

To rename a project, in the Solution Explorer, right-click its name under the solution and click Rename. Type the new name and press Enter.

Managing the Files of a Project

 

Adding a File to a Project

As mentioned already, a project can contain many files. If you are using a text editor, you can create and save files continuously as you see fit. If you are using Microsoft Visual C# 2010 Express or Microsoft Visual Studio, to add a new file to a project:

  • On the main menu, click Project -> Add New Item...
  • In the Solution Explorer, right-click the name of the project, position the mouse on Add, and click New Item...

This would display the Add New Item dialog box. From there, select the type of file you want. Accept or change its name. Then click Add.

When a project is made of various files, each file is represented by a label in the top section of the Code Editor. Here are examples:

When a project is made of various files, each file is represented by a tab in the top section of the Code Editor

Each file is also represented in the main menu under Windows.

Adding an External File

When working on a project, if there is a file in another project and you want to use that file in your project, you can import that file. To do this;

  • On the main menu, click Project -> Add Existing Item...
  • In the Solution Explorer, right-click the name of the project to which you want to import the file, position the mouse on Add, and click Existing Item...

Any of these actions would display the Add Existing Item dialog box with the name of the project on the title bar. Locate the file, select it, and click Open.

Accessing a File

If you are using a text editor to write your code, you can use that editor to open a file. For example, in Notepad, you can click File -> Open... If you are trying to open a source file, first change the file type combo box to All Files (*). Then locate the file from its folder and click Open.

In Microsoft Visual Studio or Microsoft Visual C# Express, if a file is a member of the current project, to open it:

  • On the main menu, click Window and click the name of the file
  • On the main menu, click File -> Open File...
  • In the top section of the Code Editor, click the label that holds the name of the file

Opening a File

To open a file:

  • In the Solution Explorer, double-click the name of the file
  • On the Standard toolbar, click the Open File button Open File

This would display the Open File dialog box. From there, locate the file from its folder and click it.

Renaming a File

You can change the name of a file after starting a project. To do this, in the Solution Explorer, under the project that holds the file, right-click the file and click Rename. Type the desired name and press Enter.

Removing a File From a Project

If you have a file in a project but do not need that file anymore, you can delete it. To remove a file, in the Solution Explorer, under the project, right-click the name of the file and click Delete.

Practical Learning: Managing Files in a Project

  1. If you are using Microsoft Visual Basic 2010 Express, in the Solution Explorer, right-click Module1.vb and click Delete. When asked whether you want to permanently delete, click OK.
    In either studio, to add a new file, on the main menu, click Project -> Add New Item...
  2. In the middle list, click Code File
  3. Set the Name to Management
     
    Add New Item
     
    Add New Item
  4. Click Add

Writing Code

After creating or opening a file, you can add the necessary code to it. Microsoft Visual Basic ships with many skeleton codes you can use and customize. It writes the primary code for you and add all the necessary default behaviors. Once it has done this, you can change or remove any section. To access these code skeletons, in the section of the file where you want to add it, right-click and click Insert Snippet...:

Insert Snippet

In the menu that comes up, double-click a category:

Insert Snippet

Then double-click another category. This would display a list of code types:

Insert Snippet

If you see the type of code you want to use, double-click it.

In some cases, if you have already written some code, you may want to change it or rather add some code to it. The Code Editor provides some skeleton codes you can use. To use this approach, right-click the code you want to modify and click Surround With... In the list that appears, double-click the desired option.

Practical Learning: Writing Code

  • In the empty document, type the following:
    Module Statistics
    
        Sub Main()
            MsgBox("We are performing a general census of our population")
        End Sub
    
    End Module

The Starting File of a Project

If you add many files to a project, you must specify what file should be processed first. If you create a console application using Microsoft Visual Studio or Microsoft Visual Basic 2010 Express, the first file you create is set as the default.

To specify the starting file of your project, on the main menu, click Project -> ProjectName Properties... In the Startup Object combo box, select the file.

Practical Learning: Specifying the Starting File of a Project

  1. On the main menu, click Project -> GeneralCensus Properties
  2. Click the arrow of the Startup Object combo box and select Statistics
  3. To test the application, on the main menu, click Debug -> Start Debugging
  4. Read the text of the message box
  5. Click OK on the message box

Code Colors

Code is written in a wide area with a white background. This is the area you use the keyboard to insert code with common readable characters. The Code Editor uses some colors to differentiate categories of words or lines of text.

The colors used are highly customizable. To change the colors, on the main menu, you can click Tools -> Options... In the Options dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Items section, click the category. In the Item Foreground combo box, select the desired color. If you want the words of the category to have a colored background, click the arrow of the Item Background combo box and select one:

In both cases, the combo boxes display a fixed list of colors. If you want more colors, you can click a Custom button to display the Color dialog box that allows you to "create" a color.

Indentation 

Indentation is another feature that makes your program easy to read. Indentation is a technique of grouping lines of code by category. To delimit the items of your code, you should indent them by two empty spaces or one tab. Indentation should be incremental. That is, when a line of code appears to be a child of the previous line, the new line should be indented.

To control the indentation of your code, on the main menu, click Tools -> Options... In the left list, Text Editor amd expand Basic. You can then use the options in VB Specify and Editor:

Indentation

Indentation

After making the changes, click OK to validate or Cancel to ignore.

Accessories for Code Writing

 

Comments

A comment is text that the compiler does not process when reading your code. As such, a comment can be written any way you want. In the Visual Basic language, the line that contains a comment can start with a single quote. Here is an example:

Module Module1

    Sub Main()
        ' This line will not be considered as part of the code
    End Sub

End Module

Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem, Rem, or REM would not be processed. Here is an example:

Module Module1

    Sub Main()
        ' This line will not be considered as part of the code
	Rem I can write anything I want on this line
    End Sub

End Module

Comments are very useful and you are strongly suggested to use comments regularly. They can never hurt your code and they do not increase the size of your application. Comments can help you and other people who read your code to figure out what a particular section of code is used for, which can be helpful when you re-visit your code after months or years of not seeing it.

White Spaces

When writing code, you will have to separate different parts with spaces, like the one between Sub and Main. This is referred to as white space. The amount of space you put between two words is not important. The compiler would ignore the white spaces between words. This means that Sub Main() and Sub            Main() would the same effect. In the same way

Sub Main()

and

Sub                                      Main()

would produce the same effect.

   

Home Copyright © 2008-2024, FunctionX, Inc. Monday 14 February 2016 Next