Visual Basic

From Bauman National Library
This page was last modified on 1 June 2016, at 17:18.
Visual Basic
Visual Basic 6 splash screen logo.png
Paradigm procedural, object-oriented, component-based, event-driven
First appeared 1991
Stable release 6.0
Typing discipline Static typing, Strong typing, dynamic typing
Filename extensions .bas, .cls, .frm, .vbp, .vbg
Website Visual Basic
Major implementations
Microsoft Visual Studio
Influenced by
QuickBasic, BASIC
Visual Basic .NET, REALbasic, Gambas, Xojo, Basic4ppc

Microsoft Visual Basic is a programming language and integrated development environment software developed by Microsoft. Visual Basic language has inherited the spirit, style and syntax of some of his ancestor - the language BASIC, which has many dialects. At the same time, Visual Basic combines the elements of procedure and the object-oriented and component-oriented programming languages. Integrated Development Environment VB includes tools for visual design of the user interface, code editor with IntelliSense features and syntax highlighting, as well as tools for debugging applications.

Advantages and disadvantages


  • High-speed creation of GUI applications for Microsoft Windows.
  • Simple syntax provides a low barrier to entry.
  • Ability to compile both machine code, and a P-code (the programmer chooses).
  • Type safety provides protection against errors associated with the use of pointers and memory access. This aspect makes the Visual Basic applications more stable, but also an object of criticism.
  • The ability to use most WinAPI functions to extend the functionality of the application. This issue is more fully investigated by Dan Epplmanom, wrote a book «Visual Basic Programmer's Guide to the Win32 API».


  • Support operating systems of the Windows family and Mac OS X.
  • Lack of full implementation of the mechanism of inheritance of objects. The existing language inheritance allows inheriting only interfaces, not their implementation.
  • Almost all built-in functions are implemented through language runtime library, which, in turn, produces a lot of "extra" work of verification and / or the type conversion, which slows down the speed of applications.

The language is strongly tied to its development environment and the operating system Microsoft Windows, being the only tool for writing Windows-based applications. Binding to the environment is that there is a large amount of funds intended for aid and programming convenience: a built-in debugger, view variables and data structures on the fly, the debug window, pop-up tips when typing program. All these advantages make useless or even impossible to use the Visual Basic development environment is, for example, a simple text editor

It should be noted that all the disadvantages of the language derived from its primary advantages - easy GUI development. Therefore, many programmers use Visual Basic for developing the user interface and functionality of the program is implemented in the form of dynamic link libraries written in other languages.

Language Elements

Data Types

Declaration of variables:   Dim varName As typeName

Where varName - variable name, typeName - the type. The variable type can be omitted, then the variable is declared as Variant.

Table of the main types

Name Size type Description of the type
Byte 1 byte Byte. Designed for storage of integers from 0 to 255. If this type of variable to assign a value outside these limits, then Visual Basic will generate a runtime error.
Integer 2 bytes Integer. Designed for storage of integers in the range -32768 to 32767. The suffix to indicate the type "%".
Long 4 bytes Long Integer. Designed for storage of integers in the range -2147483648 to 2,147,483 647. The suffix to indicate the type of "&."
Single 4 bytes With the single precision floating point. Range -3,402823E38 to -1,401298E-45 for negative values; by 1,401298E-45 to 3,402823E38 for positive values. The suffix to indicate the type "!".
Double 8 bytes With double precision floating point. Variables of this type can store numbers up to 16 digits in length and up to 300 characters. The range of values ​​varies from 308 to -1.80E + 1.80E + 308. Suffix is ​​"#". The calculations are approximate to it, because it uses a binary representation of the number in accordance with IEEE 754.
Decimal 16 bytes Scalable Integer. This type uses a decimal representation of numbers. Calculations with him, as well as the type of Currency are accurate. The range is -7.92E + 28 to 7.92E + 28. You can not directly declare a variable of type Decimal. It can only be used as a subtype of Variant and variable can lead to this type using the Casting CDec.
Boolean 2 bytes Boolean data type can hold only two values: True or False. The true value in VB corresponds to the integer 1, and false is 0, while the implicit type, any numeric value other than zero is treated as true. This behavior allows the use of Boolean operators AND, OR, NOT, XOR not only for Boolean algebra, but also for bit operations.
String 10 + 2 * N bytes Variable-length strings. Designed for storage of a string (character) information. The string itself is stored encoded in Unicode, so every character is encoded with 2 bytes. If you look inside the type, it uses an additional 4 bytes to store a pointer to a string of 4 bytes for the size of the string, and the string itself is null-terminated (2 more bytes). Thus the maximum size of the string can be up to 2 GB. Suffix such as "$".
String * N 2 * N bytes A string of constant length. As well as the String type stores character data, except that the data size is fixed and is specified when declaring a variable. If the string is too high, then it is truncated to the desired size. If the string is less than required, there is an alignment size of the addition of the symbol "space". It should be noted that the fixed-line and arrays and structures can not be more than 64 KB.
Date 8 bytes The data type allows you to store the time and date in the interval from midnight January 1, 100 years before midnight on December 31, 9999 year. If the variable is only attributable to a date value, the time is equal to 00:00. The integer unit is one day. It allows you to add and subtract dates using only the mathematical operators, but to fulfill these goals VB provides specialized functions to work with dates.
Object 4 bytes Used to store a reference to the object. Assigning the variable for this type occurs via operator Set. Sam is an analog type IDispatch, it stores a reference to the interface IDispatch. For any object you want to use IUnknown.
Currency 8 bytes Monetary. This type can have up to 4 decimal places, and up to 14 - in front of her. The value is a number in decimal rather than binary, as is the case for the types of floating-point single and double precision. Thus the calculation will be made accurately. The range is from -922 337 203 685 477.5808 to 922 337 203 685 477.5807. This type is preferred for financial calculations. Suffix "@".
Variant 16 bytes / 22 bytes + N Byte / N-byte Variant variable can contain any type of data including references to objects, user-defined types and arrays. Visual Basic automatically generates the necessary data conversion. Subtype containing a number requires 16 bytes of memory, and to store string data 22 bytes + length of the string. Range is the range of values ​​subtype. This type is the slowest speed performance, as it takes time to decompress and packaging values.


Array variable is declared statement of parentheses after the variable name. If you know the number of stored values, you can also specify the size of the array in the description.

Dim var1() As type1
Dim var2() As type2

Assigning values ​​to array elements:

Dim var1 (4) As String
var1 (0) = "green"
var1 (3) = "purple"

You can also assign values ​​to elements of an array in a string variable declaration:

Dim var() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9}

Extraction items from the array

Dim var1 As Integer
var1 = var (1)

The code above extracts the second element of the array var, and assigns it to the variable var1.


Assignment operator

The equal sign (=) is used to assign a value to a variable. It is also possible to use the keyword Let before the variable name (for compatibility with earlier versions). To assign a variable object type, you must have the keyword Set . Examples: nVar = 10 , Let iCount = 20 , Set refDouble = objClass .

Multiple assignment ( A = B = C ) is not possible. VB will evaluate the expression B = C in the variable A will assign the result of True or False , 0 or -1 in Depending on the type.

Arithmetic operators

  • Addition (+), subtraction (-), multiplication (*), division (/)
  • Exponentiation (^). Example: 2 ^ 3 = 8 </ code>
  • Integer division (\). Divide the first number by the second swinging (not rounding) fractional part. Example: <code> 5 \ 2 = 2
  • Modulo division (Mod). Divide the first number by the second and returns only the remainder of the division. Example: 5 Mod 2 = 1

Comparison Operators

  • = (Equal). Example: If Var = 10 Then
  • Greater than and less than (> and <). Example: If nVar> 10 Then
  • Greater than or equal to and less than or equal to (> = and <=). Example: If nVar> = 10 Then
  • Does not equal (<>). Example: If nVar <> 10 Then
  • Comparison of objects (Is). Defines object variables refer to the same object or different. Example: If obj1 Is obj2 Then
  • Similarity operator (Like). Compares the string object with the template and determine the suitability of the template. Example: If strEmail Like "*@*.*" Then

Logical operators

  • Logical AND (And) - Both of the expression must be true to the whole expression was true. Example: If (2 * 2 = 4) And (2 * 3 = 6) Then
  • Logical OR (Or) - must be true at least one of the expressions. Example: If (2 * 2 = 5) Or (2 * 2 = 4) Then
  • Logical negation (Not) - returns True , if the condition is false and vice versa. Example: If Not (2 * 2 = 5) Then
  • Logical exclusion (Xor) - in the expression E1 Xor E2 returns True , unless the E1 = True or just E2 = True , otherwise - False .
  • Equivalent (Eqv) - assesses the equivalence of the two expressions, returns True , if they have the same value.
  • Implication (Imp) - returns False , if E1 = True and E2 = False , otherwise - True .

Concatenation operator

  • (+) Operator is used to concatenate strings. If both expressions are part of a character type, the operation will be successful bonding lines. If one of the parts of the expression has a numeric type, but the other part can not be correctly converted to a number an error occurs cast. To avoid such situations, it is recommended to use appropriate operators to convert types or apply the operator (&) to concatenate strings.
  • The operator (&) produces automatic conversion of expressions and values ​​in a string type. For example, the expression str = "10" & 20 </ code> gives the result "1020" instead of "30". If using (+) operator in the expression, then VB would lead to the expression of "10" to a numeric type 10, and, if successful, would have made an arithmetic addition.

Control Structures

Operator branching


If <condition> Then 

If <condition> Then 

If <condition> Then 
ElseIf <condition2> Then 
ElseIf <uslovieN> Then 
End If

Operator selection


Select Case <verifiable value> 
    Case <value_1>'
    Case <value_2> <value_3> <value_4> 
    Case <value_5> To <zvalue_6>
    Case Is> = <value_7>
    Case Else 
End Select

Cycle with counter


For <variable> = <value> To <final_value> [Step <stepping_value>] 
    [Exit For] 
Next [variable]

For Each


For Each <variable> In <Collection>
    [Exit For] 
Next [variable]

Cycle with the condition


The loop is executed until the condition is true:

Do While <condition>
    [Exit loop] 

The cycle is executed when the condition is false:

Do Until <condition>
    [Exit loop] 

The cycle is executed when the condition is true:

While <condition>

Cycle with postcondition


    [Exit do] 
Loop While <condition>

Procedures and Functions

Routines are among the main elements of the language. They represent the procedures and functions.

  • The procedure begins with a <code> Sub and ends with End Sub , between which is placed the code. Procedures can be called by Visual Basic or other procedures and functions. Name event procedure consists of the object name, an underscore and the name of the event:
Private Sub Command1_Click () 'Event will be triggered when you press the control "button"
End Sub

Private Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single) 'Called when the mouse pointer moves on the form
End Sub
  • Functions in VB begin with the keyword Function and end with End Function . The return value of the function assigned to the variable, coinciding with the name of the function. To prematurely abort the procedure or function, there are special operators Exit Sub and Exit Function . Visual Basic 6.0 has built-in functions for working with the file system, date and time, mathematical functions, the functions of interaction with the system, functions for working with strings, functions, and features a cast performing financial calculations. There are also undocumented features that allow you to work, for example, with pointers.

Example functions:

Public Function FunctionExample (ByVal A As Double, ByRef A As Double) As Double
        FunctionExample = 8
End Function

In this example, you will notice the modifier ByVal argument to the A . This ensures that the parameters will be passed to the function 'meaningfully'. Modifier ByRef , on the other hand, conveys the value of the link. For this type of modifier, the function can modify the values ​​of variables passed as parameters. Visual Basic default value is always passed to the link, if any of the modifier was not specified.

Modules and classes

Program code stored in Visual Basic modules. There are three types of modules:

  • Module form (file extension * .frm) is the basis for most applications Visual Basic. The module contains a form event procedure, common procedures, and announced at the form level: variables, constants, types, and external procedures. If you open the form module in a text editor, you can see the description of the form and its controls, including their properties. The code is placed in the form module can refer to other forms or application objects.
  • The standard module (file extension * .bas) is a container for procedures, functions, and ads that are commonly accessed by other modules of the application. They may contain a global variable (available throughout the application) or described at the module level: variables, constants, types, external and global procedures. Code that is located in the standard module may be associated with a particular application; if not use links to form a module or control names, a standard module can be used in other applications.
  • Class Module (file extension * .cls) is the foundation of object-oriented programming in Visual Basic. Class module is used to create new objects. These objects may have its own properties, methods and events. In fact, the form - a class module, which may comprise control elements placed in it, and display them on the screen. Classes may include special procedures Class_Initialize and Class_Terminate , which is actually a constructor and destructor.

Object-Oriented Programming

Simple interaction between objects is one of the basic components of the paradigm of Visual Basic. The object is called an instance of the class. VB object model provides a variety of classes for working with forms, controls, clipboard, collection, screen, etc. To interact with other objects, class provides a developer interface consisting of properties, methods and events.

Creating a new object from the class of possible early or late binding. For early binding, use the keyword New before the class. For late binding uses the function CreateObject returns a reference to the created object. The assignment is carried out in reference to the type of variable Object , the operator using Set . Access to the methods and properties of the class takes place through an operator - point . , which is placed immediately after the variable name of the object type. If a class contains the event, the variables are declared with the keyword WithEvents , thus will be available event procedures.

Visual Basic allows developers to create new classes. Unlike other programming languages ​​such as Java and C ++, Visual Basic has an incomplete support for the PLO.

As is known, abstract class is needed to provide a template for the interface to other classes. In Visual Basic classes having the class members, but do not contain an implementation can be used as abstract classes, but in fact they are not. From class Visual Basic always possible to create an object, even if they do not contain any code.

The principle of encapsulation acts in Visual Basic. To restrict access to members of the class are the modifiers Public , Private and Friend , is used to describe procedures, functions, constants, variables and user-defined types.

Inheritance implementation is not supported. Visual Basic provides support for inheritance only through the operator interface Implements . When you inherit the interface of any class can act as the base class interface. In general, any class can act as the base class interface.

Polymorphism is provided only through interfaces, as VB does not support inheritance. The implementation of polymorphism is shown by the example of class car and aircraft implement the interface of the class Transport.

'Class ITransport.cls
Public Function GetMaxSpeed ​​() As Long
End Function
'Class CAuto.cls
Implements ITransport 'inheriting interface

Private Function ITransport_GetMaxSpeed ​​() As Long 'Implementation of the method
    ITransport_GetMaxSpeed ​​= 240
End Function
'Class CFly.cls
Implements ITransport

Private Function ITransport_GetMaxSpeed ​​() As Long
    ITransport_GetMaxSpeed ​​= 700
End Function
    Dim T As ITransport 'Declare a variable of type ITransport
    Set T = New cAuto
    WhatTransportSpeed ​​T 'is passed a reference to a procedure that invokes the class method, depending on the implementation
    Set T = New cFly
    WhatTransportSpeed ​​T

The simplest program in VB

The following console program displays the string "Hello, World!".

Module Hello
  Sub Main ()
      MsgBox ("Hello, World!") 'Displays the message "Hello, World!"
  End Sub
End Module

Important components of the program are the comments, procedure Main, input and output.


A single quote (') at the beginning of the line means that it contains a comment and the compiler should ignore it. You can make the entire line a comment or put a comment at the end of another operator.

'a comment
MsgBox ("Hello, World!") 'a comment

Procedure Main

Each Visual Basic application must contain a procedure named Main. This procedure is the starting point of the program and is responsible for general management of the application. It is called when the module is loaded.

There are four types of procedures Main:

  • Sub Main()
  • Sub Main (ByVal cmdArgs() As String)
  • Function Main () As Integer
  • Function Main (ByVal cmdArgs() As String) As Integer

The most common type - Sub Main(). When you create a Windows Forms application for applications that run on their own, you need to write a procedure Main.

Input and output

Main procedure calls the MsgBox function to display a message box containing the string "Hello, World!":

MsgBox ("Hello, World!")

External links

  1. Visual Basic 6.0 Resource Center
  2. Secure your Visual Basic 6.0 investment with Microsoft .NET
  3. Visual Basic 6 Renewed to Run on Windows 8