Visual Basic is a programming language; it is used to create
programs or applications.
A programming language is made up of a set of
sentences (understood by humans) that represent orders
given to the computer. Generally, each statement is equivalent to
many commands or instructions that the machine must carry out.
Microsoft Visual Basic is a programming tool for the
Windows environment.
The Visual Basic language is used in other applications, such as in
example Microsoft Excel, Microsoft Word, Microsoft Access, with the object
to automate routine tasks. Therefore, by knowing how to
program in Visual Basic, you will be able to create macros (in this language) in
all the previously mentioned applications and thus obtain greater
speed and efficiency in their usual tasks.
The steps to follow for programming with Visual Basic are:
1. design the forms (windows) that the user will interact with
user.
2. add the objects and define the properties of each of them.
3. establish the events that the program will respond to and write
the corresponding code (for example, define how it will respond a
button when the user double clicks
A Visual BASIC application can be made up of five classes of
files:
Form modules (.frm)
Standard modules (.bas)
Class modules (.cls)
Binary files (.frx)
Resource files (.res)
A module corresponding to a form is a file that contains
graphic objects, called controls, more code; while a
standard module or a module corresponding to a class contains only
code.
Binary files contain the binary data of a form;
For example, some controls have properties whose values are data.
binaries, like Picture.
A resource file allows you to group all the text and bitmap images.
specific to an application; may include constant declarations,
icons, screen text and other elements that may vary between
translated versions or between revisions or specific configurations.
The list of files that make up the application along with the options (the
a set of options can be seen by executing the Order Options of
Tools menu) is saved in a project file with
.vbp extension every time the application or project is saved. So
The project workspace of Visual Basic is saved in a
file with .vbw extension.
Terminology used
WINDOWS
The programs for Windows are made up of windows. The
Windows are objects. Visual Basic works with objects.
All the elements we are going to work with to develop a
programs in Visual Basic are objects and each of them has
characteristics and specific behaviors.
TYPES OF OBJECTS
There are many types of objects that Visual Basic works with, among
They can talk about the forms and controls.
A form is a window through which users interact.
with the application. In that window we will deposit the controls
necessary to create our user interface for the application. The
The main purpose of a form is to group a series of controls by
means by which to present and request information to the user.
The controls are all the objects that are placed on the forms.
through which actions are carried out. Through the controls,
They can write and receive text (labels and text boxes), use buttons
to command, insert or manipulate images, use dialog boxes,
etc.
Project
A project is a set of forms, containing controls,
objects, the properties of those objects and the Visual Basic code of
programming. That is to say, in a project they are linked.
all the components that Visual Basic uses to develop a
program.
Each of the forms contained in the project is stored
separately, in a file that will have the name of the form and the
.FRM extension. This file defines the position and dimensions of
form and each of the controls it contains, as well as the
code of the methods for those events that will be responded to.
Methods
Methods are functions specific to each object. Just like the
properties affect how objects are, methods execute
self-actions of it. The methods affect the behavior of
the objects of a program, and they are only used at runtime
execution. For example, forms have a method called Show
that is responsible for displaying them on the screen.
Events
An event is an action recognized by an object (form or control).
The event can be triggered by the user (for example: when they press
a key), by the system (for example: a certain period of time elapsed
time), or indirectly through the code (for example: when the code
load a form the Load event occurs.
Events are occurrences to which the program must respond.
In an application, many events generated by the
The user, or even the program itself, can generate other events.
In Visual Basic, each form and each control has a predefined
set of events. When one of these events occurs, Visual Basic
invoke the object's method that responds to that event.
The most important events that are common to several controls are:
Event--------------It occurs when ...
the user modifies the status of a control
Click ----------------- the user clicks an object with the primary button of the
mouse
DblClick ------------ An object is double-clicked with the primary button of the mouse.
mouse
DragDrop --------- The user drags a control to a new
location
DragOver --------- An object is being dragged over a control
GotFocus --------- An object receives focus
KeyDown --------- A key is pressed while an object has focus
KeyPress ---------- A key is pressed and released while an object has
the focus
KeyUp ------------- A key is released while an object has focus
Load --------------- An object is loaded into memory
LostFocus -------- An object lost focus
MouseDown ----- A mouse button was pressed over an object
MouseMove ------ The mouse cursor moved over an object
MouseUp --------- A mouse button was released over an object
Unload ------------ An object is unloaded from memory
Each event has a procedure for writing the code.
necessary. The name of this procedure is given by the name of the
object, followed by an underscore and the name of the event and some
parentheses. Within the parentheses are the parameters, if any
The event has some.
For example, command buttons have an event called Click,
that is triggered every time the user clicks the mouse on the
same.
The MouseMove event has parameters, its syntax is as follows:
Private Sub Form_MouseMove( Button as Integer, Shift as Integer, X as
Single, Y as Single
End Sub
This allows the procedure to know which button generated the event.
(variable Button), if the Shift was pressed (variable Shift), and the coordinates X and Y
where the mouse button was pressed.
Insertion of comments
We can insert a comment on any line, even if on it
Is there already a sentence using the character „ (apostrophe)? Any
text that appears written behind this character, until the end of the
line, is taken as a comment and will not be processed by Visual Basic.
Use of colors in the code
Visual Basic uses different colors to differentiate different parts of
a code, uses the color blue for reserved words like the word
Dim, If ...then ...else...endif, to define the name of a variable,
make assignments,... use the black color, a line containing a
error will appear in red, the comment line will appear in green. These
colors are predefined by Visual Basic, but it is possible
modify them through the Options option in the Tools menu,
In addition, you will be able to change the font type, size, etc.
Form
By default, the form title is Form1, just like its name.
These two terms, title and name, are easy to confuse.
most of the controls have a title, which we can obtain and
modify through the Caption property, which is nothing more than the text
that appears in the control, and has no correspondence or
reference in the application code.
The name of the control or form is referenced in the code each
once you want to manipulate that object. The name of a control, that is
established during the application design, will not be modified
later, and it will be used both to access the properties of
this object to perform any other type of operation with it. The
The property corresponding to the name of the object is Name.
Functions and procedures
A procedure is a set of lines of code that is given a
name, which is later used to execute this code. The
the same definition applies to a function, with the only difference being
that it returns a value upon completion of its execution, while a
procedure no.
Data types
Visual Basic has different data types, we will analyze the
next table:
Type
Boolean ---- 0bytes -------------------- True or False
Byte--------- 1byte -------------------- Integers (in the range from 0 to
255)
Integer ---- 2bytes -------------------- Integers (in the range of -
32768 to 32767
Long ------- 4 bytes -------------------- Integers (in the range of -
2147483648 to 2147483647
Single ------ 4bytes -------------------- Decimal numbers
Double ---- 8bytes -------------------- Decimal numbers
8bytes
String ------ 1 byte per character ---- String of characters
8bytes
Object ----- 4bytes --------------------- Instance of classes or objects
Variant ----- 16bytes ------------------- Any type of data
The Boolean data type (Logical) can only contain two possible values: True
true) or False(false). The value True corresponds to the integer 1 and False with the
zero value.
The Byte type is suitable for holding any non-negative integer.
greater than 255.
The Integer type is the most commonly used type, as it allows us to work with
whole numbers, both negative and positive.
The Long type (Long Integers) allows us to work with any integer numbers, both
negatives as positives, with a higher number of digits than the variable types
Integer.
The types Single (Single precision floats) and Double (Double precision floats) are the ones that allow us
use floating-point numbers, which means that the decimal point does not have a
default position, but can be anywhere it is
necessary.
The Currency type is characterized by working with numbers with a decimal part.
fixed, it has four decimal digits.
The String type (Character string) generates a variable-length string of
characters.
The Date type allows us to store dates and times, starting from January 1 of the year 100.
until December 31 of the year 9999. In reality, the internal representation of a
a variable of this type is that of a floating-point number, in which the integer part
it contains the date and the decimal part of the hour.
The Object type is capable of holding a reference to any object in the application.
for example a form or an OLE component.
A Variant variable can contain any type of data, a number, a
chain, a date, even an array, switching from one to another according to the
operational needs.
Variables
A variable is a named memory location. The name of the
position is the identifier of the variable; the value stored in the
position is called content.
Variables must be defined, declared with the DIM statement, followed by
the variable name, the word As, and the variable type.
The default value that is initialized for a variable depends on its type. If
the variable is numeric, regardless of whether it is integer or decimal and of
its accuracy, the initial value is zero. If the variable is of type String, it
the string will be an empty string. If the variable is of type Date, the date
it will be day 0 of month 0 of year 0. If the variable is of Boolean type it
initialize with the value False. If the variable is of type Variant, the value
initial will be Empty.
Variant is the default type for all variables, unless you
indicate the opposite.
A variable name must start with a letter, followed by
up to 39 additional characters, which can be digits, letters, and the character
underlined. Visual Basic does not differentiate between uppercase and lowercase.
Visual Basic allows adding to the end of a variable name, as well as
at the end of a constant, a character that refers to the data type.
It is possible to declare a variable without the As type, using
these characters.
Declaring Dato as Integer is the same as writing Dim Dato%
Visual Basic Modules
The code of a Visual Basic application is edited in modules. The
modules have built-in automatic formatting functions and
syntax check. There are three types of modules: form,
standard and of class.
Form module
It is a file with a .frm extension that can contain descriptions
graphs of a form, its controls and their property values,
declarations of constants, variables, and external procedures at the level
from the form, as well as procedures conducted by events and
general procedures.
Standard module
It is a .bas file that only contains declarations and
definitions of procedures, types, and data they have access to
other modules of the application.
Class module
It is a file with a .cls extension that contains the definition of a class.
of objects; that is, the definition of each of its properties and
methods.
Scope of the variables
The scope or range of a variable refers to the space of the
application where the variable is visible and therefore can be used. A
The following are the places where one can declare a
variable
-Variables used by all modules (Public declaration in
any module)
Module (form, standard mod. or class)
-Variables used within the module (Dim or Private declaration in the
module)
-Procedures: Local variables (Dim o Static) - Local variables (Dim
Static
The following table summarizes how to declare a variable based on
of the space where we want it to be visible:
Scope Declaration
Local Dim o Static (inside a procedure)
Private Dim Module (module declarations section: section
General)
Global Public (section of statements of a module)
At the module level, there are no differences between Dim and Private, but it is advisable to use
Private in contrast to Public. In a procedure, this observation does not take place.
since Public cannot be used.
Local variables
A local variable is recognized only in the procedure in which it
is defined. Outside of that procedure, the variable is not known.
A local variable is reset every time it is entered.
procedure. A local variable does not retain its value between calls
to the procedure and the following. However, this can be modified.
By means of the Static statement, the static variable must be declared. Visual
Basic initializes a static variable only the first time it is called
the procedure and is destroyed only when the application ends. For
to declare a static variable, use the keyword Static instead of
Dim.
Global variables
Global variables are those that can be used from
any point of the application, regardless of the module it is in
procedure that accesses it.
It is only possible to declare a global variable at the module level, that is,
outside of any procedure or function using the Public statement,
followed by the variable name, the word As and the type of variable. If
it tries to declare a global variable inside a function or a
the procedure will encounter an error during the compilation of the application,
he will not even be able to execute it.
The lifetime of a global variable begins at the same moment
in which the application is loaded, and it does not die until it finishes.
Constants, Variables, and Expressions
Variables can be global, accessible from any point,
public in a module, accessible from methods and functions
contained in a code module, or private, accessible only in the
scope in which it has been declared.
It is a common practice that all variables used in
methods and functions are kept private, thus preventing them from being
manipulated from any external code. These types of variables are
automatically created every time the procedure is executed or
function, and destroy them when it ends. This fact, on the other hand,
reduce global memory consumption, as most of the
variables exist only while the portion is being executed
code in which they are declared, and the memory they occupy is released upon exiting.
A constant is a named memory position. The name of the
position is the identifier of the constant; the value stored in the
The position is called content and cannot change during execution.
from the application. Constants must also be declared with the
CONST statement, followed by the name of the constant, the word As and the
type of constant, the sign = and the assigned value.
Example: Const MATERIA as String = "computing"
To be able to use Visual Basic 2010, follow these instructions:
What I am showing you on screen is VB Professional 2010, but no
Import Express will serve in the same way for what it
we will use.
The first application we will create is an application that will help us
It will show a message.
Step 1
We will need to place a Textbox and a Button. You will find them in the
left part of the screen.
The next step is to name the button. They will go to the bottom right.
in the properties, they will look for where it says Text. And they will change it
name.
Now we will double-click the button we placed and it will appear.
a screen something like this:
Step 2
Now we will name a Variable, as I mentioned in the first
tutorial, we should give a meaningful name to the variable. For
to name a variable in Visual Basic we will use Dim followed by the
name of the variable, which in my case I will call "Word" and it is followed by the Type
given that for the program's requirement, it will be String, and in Visual
Basic is a String since we are using words for the output.
Step 3
After naming the Variable, we will assign a Value to the variable.
To do this, we write the variable name and then the sign of
equality (=) and since it is a String, the value will be placed in quotation marks (" ")
In my case I wrote 'This is the first Programming Tutorial'
Put whatever you want.
Step 4
It is the output, since we placed a Textbox and that is where it will appear.
message, we will write the name of the Textbox, followed by .Texty
followed by the equal sign (=) and then the name of the variable.
A summary of what we did:
We place a Button and a Textbox in the interface.
We went to the programming area
3) We name the variable using (Dim "The name of the variable"
As String)
4) We assigned a Value to the Variable Placing("The name of the
The desired value
5) We write the (Textbox Name followed by .Text the Sign of
equality (=) and "The name of the variable"
Now the last step is to test it, we will click the green symbol on
upper part.
Fill a DataGridView
This example shows how to fill a DataGridView from
a table, without having previously created the columns.
It's part of a form that includes a DataGridView, without
configure no column.
Both the columns and the rows will be appended through code.
The final result will be a DataGridView, which will contain all the
columns that the query returns from the database. Including the
possibility to add others through code.
CLARIFICATION:
In the case of knowing how many columns the query will return, we
they can add one by one with the
instruction [Link], passing as a parameter the
name of each column
same.
It is usually common for both to be the same, although it is not essential.
With this, the name of the table can be recovered:
[Link]([Link](0), [Link](0))
Or you can assign any name you like:
[Link]("Column Name", "Header Text")
Column
In case you do not know how many columns the query will return, it is
it is possible to create a loop that adds columns until reaching the value
indicated by the reader, in the FieldCount property.
For i As Integer = 0 To [Link] - 1
[Link]([Link](i), [Link](i))
Next
Regarding the process of filling in the rows, they can be added as
shown in the previous example or using a string table
characters.
The detail shows this solution:
[Link]("Amount", "Amount")
Dim tabla_cadenas([Link]) As String
While [Link]()
A row is added to the grid with a string for each column.
For j As Integer = 0 To [Link] - 1
table_strings(j) = [Link](j).ToString
Next
[Link](string_table)
End While
---------------------------------------------------
Code example
---------------------------------------------------
1 - Import namespace
Imports [Link]
Public Class Form5
Private Sub Form5_Load(ByVal sender As [Link], ByVal e As
[Link]) Handles [Link]
2 - create connection
Dim connection As New OleDbConnection
3 - connection string
[Link] =
Provider=[Link].12.0;Data
Source=C:\factura_cliente.accdb;Persist Security Info=False;
4 - open connection
[Link]()
5 - create the SQL statement
Dim comando_SQL As New OleDbCommand("SELECT * FROM "
Invoice_lines WHERE Invoice_number_fk = " & Form2.invoice_number
connection)
6 - the reader is created
Dim lector As OleDbDataReader = comando_SQL.ExecuteReader
' *****************************************************************
7 - Show reader values in the DataGridView
[Link]()
[Link](0).HeaderText = [Link](0)
[Link]([Link](0),
[Link](0))
[Link]([Link](1),
[Link](1)
[Link]([Link](2),
[Link](2)
[Link]([Link](3),
[Link](3)
[Link]([Link](4),
[Link](4)
Another option to add columns
For i As Integer = 0 To [Link] - 1
[Link]([Link](i),
[Link](i)
Next
[Link]("Amount", "Amount")
Dim table_strings([Link]) As String
While [Link]()
A row is added to the grid with a string for each column
[Link]([Link](0), [Link](1),
[Link](2), [Link](3), [Link](4)
For j As Integer = 0 To [Link] - 1
table_strings(j) = [Link](j).ToString
Next
[Link](string_table)
End While
final point close connection
[Link]()
Dim total_invoice As Single
Dim partial_invoice As Single
Subtract 2 from [Link] to discard the line in
white
For i As Integer = 0 To [Link] - 2
partial_invoice = CSng([Link](i).Cells(3).Value) *
CSng([Link](i).Cells(4).Value)
total_invoice += partial_invoice
[Link](i).Cells(5).Value = partial_invoice
Next
'**********************************************************************
Form2.invoice_number
Form2.invoice_date
Form1.customer_code
Form1.fiscal_Name_data
Form1.data_Cod
Form1.Address_Data
Form1.commercial_Name_data
Form1.fiscal_Name_data
total_invoice.ToString
End Sub
Private Sub Button1_Click(ByVal sender As [Link], ByVal e As
[Link]) Handles [Link]
[Link]()
End Sub
End Class
Delete a record from a database
In this example, it is indicated on one hand how to read and display the data of
a table, one by one.
Instead of reading from the DataReader using a While loop, one
execute a read from the DataReader for each button press.
7 - Show reader values
[Link]()
Data is added to the textboxes.
[Link] = [Link](0).ToString
[Link] = [Link](1).ToString
[Link] = [Link](2).ToString
[Link] = [Link](3).ToString
[Link] = [Link](4).ToString
On the other hand, it shows how to handle the process of elimination of a
record, trying to prevent data from being accidentally deleted,
showing a MessageBox that requests confirmation of the deletion
of the record, but has the cancel button assigned by default,
to prevent an erroneous press from causing accidental deletion
from a record.
[Link]("Do you really want to delete client number " &
[Link] & "?", "Record Deletion"
[Link], [Link],
MessageBoxDefaultButton.Button2
Finally, it shows how to use a delete query.
Dim comando_SQL As New OleDbCommand("DELETE FROM Clientes")
WHERE Id_cliente =
------------------------------------------------------
------------------
CODE
------------------------------------------------------
------------------
1 - Import namespace
Imports [Link]
Public Class Form3
Public reader As OleDbDataReader
Private Sub Form3_Load(ByVal sender As [Link], ByVal e As
[Link]) Handles [Link]
2 - create connection
New OleDbConnection Dim conexion As
3 - connection string
[Link] =
Provider=[Link].12.0;Data
Source=C:\factura_cliente.accdb;Persist Security Info=False;
4 - open connection
[Link]()
5 - create the SQL statement
Dim comando_SQL As New OleDbCommand("SELECT * FROM ")
Clients ORDER BY Client_Id
6 - the reader is created
reader = sql_command.ExecuteReader
' *****************************************************************
7 - Show reader values
[Link]()
Data is added to the textboxes
[Link] = [Link](0).ToString
[Link] = [Link](1).ToString
[Link](2).ToString
[Link] = [Link](3).ToString
[Link](4).ToString
'**********************************************************************
final point close connection
[Link]()
End Sub
Private Sub Button1_Click(ByVal sender As [Link], ByVal e As
[Link]) Handles [Link]
If [Link]() Then
A row is added to the grid with a string for each column
[Link] = [Link](0).ToString
[Link] = [Link](1).ToString
[Link] = [Link](2).ToString
[Link] = [Link](3).ToString
[Link] = [Link](4).ToString
Else
All records have been displayed
End If
End Sub
Private Sub Button2_Click(ByVal sender As [Link], ByVal e As
[Link]) Handles [Link]
2 - create connection
Dim connection As New OleDbConnection
3 - connection string
[Link] =
Provider=[Link].12.0;Data
Source=C:\factura_cliente.accdb;Persist Security Info=False;
4 - open connection
[Link]()
If [Link]("Do you really want to delete customer number
Are you sure you want to delete the record
[Link], [Link],
MessageBoxDefaultButton.Button2) = [Link] Then
5 - create the SQL statement
New OleDbCommand("DELETE FROM
Clients WHERE Id_client = "
Dim total_affected_data As Integer
6 - The query is executed
total_data_affected = SQL_command.ExecuteNonQuery
[Link]("Successfully deleted " &
total affected data & ' records.')
Otherwise
Deletion canceled.
End If
End Sub
End Class
1 - Introduction
All languages use this system or methodology for the
application programming, but they vary in how they
they use, their syntax etc...
When one first starts programming, it seems very
complicated to understand these topics, but with practice everything becomes
make it clear.
The good thing about understanding the fundamentals of programming,
it allows us to then program in almost any
language, because the way of programming in general does not vary
too much, what changes in each of them is their syntax and
functions and peculiarities of the language. Although it is not that
thus, this does not mean that just because one is an expert
example programming in C language, whether in Visual Basic and
Vice versa.
2 - The Variables
Variables, as their name indicates, are used to
store values that have the property of varying the
content. When we talk about content, we refer to
any type of data, for example a name, a date, a
color, a number etc... .
Variables are assigned a name so they can be used.
For example, I can create a variable called date and this
it will store a date. The variable names are
denominated identifiers. When we create variables, we have
to try to assign them a name that relates to the type
of the data we want to store. For example, it would not have
it makes a lot of sense to create a variable called my and store or
store a name or a surname, because when we throw
viewing the code would make it more difficult to infer what kind of data
I am saving. For example, in this last case it would be a lot.
it makes more sense to create a variable called 'names' and store there
"Luciano", "Pedro", "Natalia" etc..
In Visual Basic, it is advisable to declare variables, that is,
to inform vb that we are going to use said variables. To these are
declared at the beginning of the code and is preceded by
the reserved word Dim, then the name that we
we want and then the type of data that will be stored, for
for example if I want to store in a variable called number
Dim number As Integer
The word Integer warns Visual Basic that I am going to save
an integer. After declaring it, we can assign it
a value with the operator "=", example:
Declare number as Integer
numero = 1500
But it should be noted that when declaring a variable, in
in this case, of integer type, we could not store in it a
string of characters such as a name or anything
data type that is not an integer. If
this would happen our program would throw a runtime error
execution, showing us an ugly sign telling you no
the data types match.
3 - Data types:
Data types indicate the type of value that can be
store a variable. The main data types:
Integers: within the integers we have
various types of data depending on the range we want
to use
Byte: can store integer numbers within the range
from 0 to 255
Integer: can store whole numbers inside the
range -32.768 to 32.767
It can store integer numbers within the range
-2,147,483,648 to 2,147,483,648.
Decimal numbers: to store decimal numbers
we have the following types of data:
Single: stores decimal numbers in the range +/- 1e-
45 to 3e38
Double: from +/- 5e-324 to 1.8e308
Character strings: character strings are defined
with the word Stringy they have a range of up to 2 billion
characters.
Types of logical values: for storing types of values
logical as true or false, the word Boolean is used
Its 2 possible values are True (true) and False (false).
Dates and times: To store dates and times, the
wordDate
Type variant: Variables of this type can store
any type of value, but they take up more memory.
Note: there are more types of data, we can even create them ourselves.
ours
4 - Constants:
Constants, like variables, are used to store
data and values for our program, but unlike
these last ones (the variables), the content they store does not
Change is always constant.
Unlike the variables that are declared with the
Constants are declared with the word
Const.
Example:
const number = 53
In the previous line, I created a constant, which I called
number and it will store a number, and this value, when it
execute my program will remain unchanged.
An example:
1 - In the following line, 2 types of variables of type are declared.
Integer num1 and num2. Then a value is assigned to them.
each one and then we sum them, and through the MsgBox function
What is a Visual Basic function to display messages?
we show the result of that sum.
Place a button (CommandButton) named Command1. Do
double click on the button to open the code window
from Visual Basic. Within the Click procedure paste this
code:
Dim num1 As Integer
Dim num2 As Integer
num1 = 10
num2 = 20
a message will be displayed with the sum of the
variables with the result 30
MsgBox num1 + num2
When you run the program, you can see how a box is displayed.
of message with the result of adding the 2 variables num1 and
num2
2 - Now we are going to declare and create 2 String type variables,
That is to say, we are going to store character strings in each one.
of them. In the example, 2 variables are created, one
they call it a name and another last name. Then we assign it a
value, and finally we display the variables with a message
using the MsgBox function as in the previous example. But
First, it is important to clarify something, the strings in visual
Basic ones are enclosed in double quotes as you can see in the
example, otherwise an error will occur.
Dim name As String
Dim lastName As String
the we establish values
Carlos
Peres
we show a message with the value of the
variables
MsgBox name
MsgBox last name
3 - Now an example that produces a runtime error
execution. We create 2 variables exactly like in the
previous example, but instead of declaring the variables name and
last name as type String we make it as type
Integer.
Dim Name As Integer
Dim LastName As Integer
The we establish values numerical
Carlos
Peres
If you try the example, Visual Basic will show you a message of
error such as the following: "data types do not match":
...since the variables are declared as type Integer, and
you are assigning a data type that it does not accept.
4 - An example that stores a number in a variable
of type Byte (numbers from 0 to 255). First we declare the
variable y we give it a name, for example if we want
to store the number 88 we do it like this, for example.
Dim Age As Byte
To assign a value to that variable:
Edad = 88
To show the value of the variable Age in a TextBox control
when we press a button Command1, it would be like this
way
Private Sub Command1_Click()
We declare the variable
Dim Age As Byte
We assign it a value that is not less than 0 or
mayor a 255
Edad = 88
We show it in the control called Text1
Age
End Sub
If you tried changing the value 88, for example to 300, this would happen.
the same as in the previous example, that is to say an Error 13 in
runtime "Data types do not match"
5 - Control structures:
Control structures are used to control the flow
of the program in a routine or function. Through them we can
control, through a condition, that an execution occurs
a certain line or block of lines of code .. or that is not
execute.
If - Then - Else structure
This structure allows, through a condition, to be executed
or a specific task or line of code is not executed.
For example, let's suppose we have in a form a
Control label with the property Caption with the value 50
If [Link] = "50" Then
my label has a value of 50
else
msgbox "my label does not have a value of 50"
end if
This translated into Spanish would mean the following:
If the caption property of label1 that I have on the form
is equal (=) to '50' then show a
determined message, if not (Else) show the other
message.
In conclusion, what this structure does is evaluate a
condition, if met, that a specific task is executed. if not
it is fulfilled, the lines of code that are under will be executed
Else clause. Then we have to close the structure with the
wordend if.
We need to clarify that it is not mandatory to use If and else.
together in the same clause. For example, we could use
just an If structure without else. For example:
Private Under Command1_Click()
If the caption property of Label1 is 'Hello'
then the program ends
If [Link] = 'Hello' Then
End
End If
If not, we continue with this line
MsgBox "The previous If block did not execute because"
the Caption of control Label1 was not Hello
End Sub
Place a Label1 and a Command1. In the caption property of the
Label1 writes 'Hello'. When running the program and pressing the
Command1, the program ends with the End statement.
Visual Basic (End is used to completely terminate the
execution of our program). On the other hand, if it changes now
the caption to Label1 and run the project again, you can see
that the End instruction is not executed, but rather it is overlooked and
continue with the remaining lines, in this case execute the function
Message box with the message.
While - Wend Structure
This control structure will repeat without stopping a
a certain code while a condition is met.
For example, let's assume we have a variable
it is called a value of 100.
while x = 100
...all lines of code are executed that
be here
wend
This translated into Spanish would mean the following:
While the variable x is equal to 100, and does not change its
value, an endless loop will form, until it switches to
any other value different from 100. If x changes the value, by
example to 234 would exit the While - wend loop and continue
executing the rest of the code, if there is more code or
instructions to execute.
An example, add a Command1 to the form and a
controlText1. When we run the example, it should
write a number inside the textBox control. Then it
It will create a While loop that will display in the Caption of the
form, that is, in the title bar, the interval from 0
until the number we have entered in Text1. That is, if
we enter the number 9000, in the caption of the form
they will print the numbers from 0 to 9000.
To do this, within the While loop we will put a
variable called Counter, which in each pass
will increase by 1, but when the variable Counter is equal
the number that is in Text1, the loop will be terminated and it
it will show a message that it has finished
Private Sub Command1_Click()
Dim counter As Integer 'We declare the variable
While counter <> Text1
We show the value of the in the form
variable counter
[Link] = counter
We increment the variable by 1
accountant = counter + 1
Wend
MsgBox It ended the loop
End Sub
For - next structure
The structure is used to generate a repetition of
instructions or loop, but does not evaluate a condition as in the
case of the While loop, instead it does so between an initial number and
a final number that we must indicate to it.
For example, we have a form with a Label1 and we declare
an integer type variable called "counter" as in the case
anterior
Private Sub Command1_Click()
Dim counter As Integer
For counter = 0 To 1000
[Link] = counter
Next counter
End Sub
This translated would mean the following:
First, we have a variable called 'counter'. Through
the loop For - next we can control the number of times that
we want to repeat a certain process or instruction. This
it has a beginning and an end, in this case the beginning would be 0 and the
fin 1000, so that the counter variable
will increase by 1 until it reaches 1000, and will repeat 1000
sometimes all the instructions that are under the For clause
next. In this case, our control Label1 would display the
content of the counter variable
To see this in detail and step by step, let's put a
example that repeats 10 times (from 1 to the
10 in the loop interval For) and will display a message with the
value of the variable Counter. Once it reaches 10,
it will end.
Place a Command1. Double click on the button to write
within the procedure that will be executed when it
Let's press. The code:
Dim accountant As Integer
For counter = 1 To 10
MsgBox "The variable Contador is: " &
counter
Next counter
End of For loop
Select case structure
The structure Select Case is usually used to avoid the use of
many If clauses and this way not having to nest them. The
SELECT clause evaluates a condition y the
case clauses contain values, if the value they contain
clause case equals the condition that was evaluated, will execute
the instructions in that clause.
Dim Name As String
Name = Text1
Select Case Name
Case Jorge
MsgBox "The case clause was executed: " &
Name
Case Pedro
MsgBox "The case clause was executed: " &
Name
Case Carolina
MsgBox "The case clause was executed: " &
Name
End Select
This structure is very practical. In the previous example, the
The select case clause contains as a condition the value of the
variable calledName. That Variable takes the value it has
a control Text1, then it will search in all the case clauses,
and if it finds one that matches the condition, it will only execute the
instructions of the case clause that has the same value, by
for example, if I entered the name 'Martín', nothing will happen
Case clause. On the other hand, if I enter 'Jorge', only the execution will occur.
instructions that are in the section Case 'Jorge' and so on...
In the previous case, we have only placed a value for each
Case. If we wanted to add more values, we could do it by
this way:
Private Sub Form_Load()
Dim x As Integer
x = 10 'We assign a value to x
Select Case x
Case 5 10
MsgBox "The case with 5 and 10 was executed"
If execute this section
Case 15 20
This no himself execute
Case 25 30
This neither
End Select
End Sub
that is to say we can list the values in the Case separated
by commas. In the previous case, case 5, 10 will be executed
that the variable x is equal to 10
6 - Visual Basic Operators
Operators allow us to operate, validate, compare, assign,
distinguish, etc.., the data and code instructions from our
Programs. Next, the most important operators.
Arithmetic operators
These operators allow us to work with calculations.
mathematics such as addition (+), subtraction (-), division (/), and
multiplication (*).
Examples:
a = 5
b = 15
c = a + b in this case the variable c would contain
the value 20
ganancia = 500
perdida = 200
total = gain - loss the variable total
it would be worth 300
x = 100
y = 20
z = x / y' The variable z is equal to 5
x = 100
y = 20
z = x * y' The variable z equals 2000
Logical operators
They are used in expressions to return results of the type True
or False, that is True or false. The most common are the
operator Andy the operator Or
Examples:
If (x = 10) And (name = "maria") Then
only the code within this block will execute
IF yes the variable
x is worth 10 and the variable name is equal to María
End If
If (m = 10) Or (name = "pedro") Then
the code will execute if at least one
variable it correct
that is to say if at least one condition is met
End If
Comparison operators
Comparison operators are used to compare
expressions of any kind. The most important are: The
operator = less than, greater
than(>), different from(<>)
Examples:
If [Link] = "06/08/1978" Then
if the control label1 in its caption contains that
date
the code that is here will be executed
End If
if x > 6 then
if the variable x is greater than 6 the will be executed the
code what this here
end if
If country <> "United States united" Then
if the country variable is different from 'States
"united" will execute the code
End If
While c <= 87
while variable c is less than or equal to 87
will execute
the loop While
Wend
By last would remainfor see the operator of
concatenation (&) that is used to join strings of
characters.
For example:
Jose
Peralta
name & surname
The variable fullname would contain the
union of the other two variables
that is to say Jose Peralta