Saltar al contenido
Underc0de /foro

VB - basic student guide.

🌐 This is an automatic translation of a topic from Underc0de, the largest Spanish-speaking hacking and IT community. Read the original (Spanish) and reply →
Alex ·
Madrid, July 1998<br />SOURCE (www.monografias.com)<br /><br />Visual Basic - Student Guide Ch. 1<br /><br />INTRODUCTION Historical background.<br /><br />The BASIC programming language (Beginner's All purpose Symbolic Instruction Code) was born in 1964 as a tool aimed at beginners, seeking a simple way to write programs, using a language almost identical to the one used in everyday life (in English), and with very simple and few instructions. Considering the year of its birth, this language covered almost all the needs for running programs. Keep in mind that the machines of that era were just debuting transistors as switching elements, work cycles reached the unthinkable figure of 10,000 per second, and memory did not exceed a few k´s in ferrite toroids.<br /><br />The evolution of BASIC during the 70s was limited, given the boom that high-level languages like FORTRAN and COBOL had at that time. In 1978 a standard was defined to unify the existing Basics, creating the BASIC STANDARD specification
Alex ·
General Features of Visual-Basic<br /><br />Visual-Basic is an application design tool for Windows, in which applications are developed largely starting from the design of a graphical interface. In a Visual - Basic application, the program is made up of a part of pure code, and other parts associated with the objects that make up the graphical interface.<br /><br />It is therefore a middle ground between traditional programming, made up of a linear succession of structured code, and object-oriented programming. It combines both trends. Since we cannot say that VB belongs entirely to either of those two types of programming, we must invent a word that defines it: VISUAL PROGRAMMING.<br /><br />Creating a program in Visual Basic involves the following steps:<br /><br />- Creating a user interface. This interface will be the main channel of human-machine communication, both for data output and input. It will be necessary to start from a window - Form - to which we will add the necessary controls.<br /><br />- Defining the properties of the controls - Objects - that we have placed on that form. These properties will determine the static form of the controls, that is, what the controls are like and what they are for.<br /><br />- Generating the code associated with the events that happen to these objects. We call the response to these events (click, double click, a key pressed, etc.) a Procedure, and it must be generated according to the needs of the program.<br /><br />- Generating the program code. A program can be made solely by programming the different procedures that accompany each object. However, VB offers the possibility of establishing program code separate from these events. This code can be entered in blocks called Modules, in other blocks called Functions, and others called Procedures. These Procedures do not respond to an event that happened to an object, but rather respond to an event produced during the execution of the program.<br /><br />It is not necessary to understand the above for now. Visual Basic introduces a new programming concept, and it is necessary to change even the programmer's jargon. You may have been hit with too many terms at once. That's normal. If you keep reading a little you will see things more clearly when they are explained one by one.<br /><br />--------------------------------------------------------------------------<br /><br />VARIABLES. DEFINITION AND SCOPE<br /><br />Basic, unlike other programming systems, has never required the prior definition of a variable. A variable, as you surely know, is a name that we assign to a piece of data in the program. That data may change. Think, for example, of a program that collects data on the students of a school. There will be several variables to enter the students' data. These variables may have names such as:<br /><br />
Código: text
Nombre<br /><br />Apellido1<br /><br />Apellido2<br /><br />Dirección<br /><br />Teléfono<br /><br />DNI
<br /><br />The variable Nombre will take different values as we enter the data of the different students. It is possible that throughout the execution of the program, this variable Nombre will be:<br /><br />
Código: text
José<br /><br />Pedro<br /><br />María<br /><br />Luis
<br /><br />I hope your intuition or prior knowledge leads you to understand the concept of a variable. Later on you will see it more clearly.<br /><br />We said that Basic does not require variables to be defined beforehand. Other tools require it. Therefore it is normal to find, in other programming systems, that a program begins as follows:<br /><br />
Código: text
Declare Nombre As String Le dice que Nombre es una sucesión de letras<br /><br />Declare Apellido1 As String<br /><br />Declare Apellido2 As String<br /><br />Declare Dirección As String
<br /><br />Declare Teléfono As String Tells it that Teléfono is a sequence of letters<br /><br />
Código: text
Declare DNI As Número Le dice que DNI es un número
<br /><br />Through these declarations, the program knows what type of data it is and therefore how it should work with it. In programming systems other than Basic, it is necessary to make this declaration before introducing a variable.<br /><br />Basic allows them not to be declared. When we introduce a new variable throughout the program, it assumes that it is a variable and that its type is appropriate for the value we are entering at that moment.<br /><br />For example, if Basic finds these instructions<br /><br />
Código: text
DNI=50000000<br /><br />Nombre ="Pedro"<br /><br />Teléfono = "1234567"
<br /><br />it understands that DNI, Nombre and Teléfono are variables, that DNI is a number (we did not put its value in quotes), and that Nombre and Teléfono are sequences of alphanumeric characters (their value is in quotes)<br /><br />This peculiarity of not needing to declare variables makes it easy to introduce a new variable. However, it carries a great danger. Imagine that in a later step of the program, we tell it to write those three previous pieces of data with the PRINT instruction<br /><br />
Código: text
Print DNI<br /><br />Print Nombre<br /><br />Print Telefono
<br /><br />You will have noticed in third place the word Telwfono, which the programmer introduced by mistake. Basic interprets that Telwfono is a variable and will go read the value it has in memory. It will have no value. Therefore it will write nothing and on top of that will give no warning that an error has been made. Nothing is free in this life, and the ease of introducing variables is paid for with the possibility of error.<br /><br />Basic has thought about this problem, and it can be solved with what will be the first BASIC instruction we are going to study:<br /><br />OPTION EXPLICIT<br /><br />It forces you to declare beforehand the variables that are going to be used. If you have not declared one before using it, the program will report an error.<br /><br />TYPES OF VARIABLES<br /><br />Variables can be of the following types: (The number indicated in second place indicates the number of Bytes it occupies in memory.)<br /><br />
Código: text
Boolean (2) Admite los valores 0 y 1, o True (verdadero) y False (falso)<br /><br />Byte (1) Números enteros, en el rango de 0 a 255<br /><br />Integer (2) Números enteros en el rango de -32768 a 32767<br /><br />Long (4) Números enteros en el rango de -2147483648 a 2147483647<br /><br />Single (4) Punto flotante, simple precisión<br /><br />Doble (8) Punto flotante, doble precisión.<br /><br />Currency (8) Entero, con punto decimal fijo (Típico de monedas)<br /><br />String (*) Cadenas alfanuméricas de longitud variable o fija<br /><br />Date (8) Fechas<br /><br />Objet (4) Referencia a objetos<br /><br />Variant (**) Otros tipos de datos
<br /><br />(*) A String variable occupies the same number of bytes as there are characters in the string.<br /><br />(**) A Variant variable occupies 16 bytes if it is a number and 22 bytes + the length of the string if it is a character string.<br /><br />There are also user-defined variables (you'll see the Type statement). In this type of variable you can put many pieces of data of different types. The bytes needed to store that variable will depend on the data that has been defined.<br /><br />Within Objet variables (variables that refer to objects) there is a great variety that at this point in the course we shouldn't complicate ourselves with. But to give a preview, we will see that a variable can be of type Form, type Picture, etc. etc.<br /><br />Each type of variable occupies a certain number of bytes. If a variable is not defined, VB takes Variant as the default type for the variable. This type occupies more bytes than, for example, an integer. If the type of data we are going to put in a variable is an integer, and we have not declared it as such, VB will assume that variable is of type Variant, which will lead it to use more bytes of memory (16) than it would need (2) if we had declared it beforehand. If that variable is going to be in the range 0 to 255, and we don't declare beforehand that the variable will be of type Byte, or we declare it as integer, e.g., we are wasting RAM and possibly slowing down program execution. The same can be said of the rest of the variables, and how important it is to define them and define them well.<br /><br />NOTE. Notice in the list above that a Boolean value occupies 2 Bytes, while a Byte value occupies one byte. On many occasions we declare Boolean variables with the intention that they take up less space. A VB paradox. If we declare it as Byte we take up less memory. Declaring a variable as Boolean also has its advantages (you will generally write less code when you need to read or write a Boolean variable), but keep this observation about Boolean data in mind.<br /><br />You can declare the type of the variable by means of a character after the variable name. This technique, mandatory in Quick-Basic, has fallen out of use in VB. It is not advisable to define the type this way, as there is a serious risk of error. In any case, that is up to the programmer and their habits.<br /><br />The characters that define each type of variable are:<br /><br /><br />
Código: text
% Integer & Long ! Single<br /><br /># Double @ Currency $ String
<br /><br />Practical Examples of variable declaration<br /><br />In Visual Basic, when we declare a variable as String (character string), it is not necessary to declare its length. VB will accept any number of characters. If you want to prevent more than a certain number of characters from being entered, you must declare that number. For example:<br /><br />
Código: text
Dim Var1 as String Var1 puede tener cualquier número de caracteres<br /><br />Dim Var2 as String * 15 Var2 puede tener un máximo de 15 caracteres.<br />
<br />In this second case, if a string with more than 15 characters is entered as Var2, Var2 will take only the first 15. Visual basic gives no warning that this variable has omitted the characters beyond the figure of 15. If you want the user to know about that, you must add the appropriate code to produce the warning.<br /><br />Declaring String variables with a predefined number of characters also has drawbacks when handling that string with statements such as Mid, Left and Right, or when appending one string to another. Experience tells us that it is NOT worth declaring String variables with a fixed number of characters.<br /><br />In a large number of cases, a variable made up of numbers should be declared as a character string variable (String), and not as numeric. When we think for example of an ID (DNI) number, made up of 7 or 8 digits, a postal code, a street number, the floor of a building, they seem to invite the variable containing them to be of a numeric type (Byte, Integer, Long, ...). These variables, even though their content is numbers, should always be declared as String, since they are really character strings, even if those characters are numbers. To clarify these ideas further, think of the DNI number with the NIF letter included, or that the DNI field has to be filled with a residence permit number (it has letters). Think of the postal code of a province that begins with 0 (08XXX = Barcelona). If the variable that will contain that postal code is declared as numeric, the leading zero is discarded, so that postal code would be reduced to 8XXX, a 4-digit number that the postman would never recognize as a postal code, which must have 5 digits. Finally, think about how to put the street number 32Bis or the floor S2 of a building into a numeric variable. Or think of a variable that will contain a product code. That code will always be a number, for example of 9 digits. Have you thought about how the computer would handle a numeric variable containing the code 000100123? The result would be that it would convert that code into the figure 100123, and you would have to figure out how to add the leading zeros when sending it to a printer, for example.<br /><br />In all the above cases, the number does not represent a numeric quantity, but a name. It just so happens that this name contains only numbers.<br /><br />Which variables should we declare as numeric, then? The answer is very simple: those that are going to contain data with which we will perform mathematical operations.<br /><br />Boolean variables (True/False) can in many cases be replaced by a Byte variable. If that True / False data is going to be entered into a database or a file on disk, it may be more prudent to put 0 instead of False and 1 instead of True.<br /><br />A byte variable takes up very little, just 1 byte as its name indicates. But it cannot contain numbers greater than 255 or negative numbers.<br /><br />Every time you declare a numeric variable, think about the values it can have, especially when that variable is going to be the result of a mathematical operation. Remember the narrow range of an Integer variable (from -32768 to 32767)<br /><br />If the application is going to handle currency, think about how to express decimal numbers and how many of them are allowed, as well as rounding. The correct variable for this case is Currency, but Currency automatically adds each country's currency type (Pts. for Spain), which is often a nuisance. It takes the currency data from the computer's operating system, so don't be surprised if it expresses the number of pesetas in dollars. Change the country in your OS.
Alex ·
Scope of variables.<br /><br />We call the scope of a variable the parts of the program where that variable is declared. To understand it better, let's briefly look at the shape of a program developed in VB.<br /><br />A VB program has one or more forms. Each form has several controls. Both the form and each of its controls have a part of the program, precisely the part related to each of the events that can happen either to the form or to the controls. We had called these parts Procedures. We can have procedures that are not related to any event happening to the form or its controls. (The Procedures that we will be inserting throughout the application)<br /><br />Apart from forms and controls, a program can have Modules, and in each module we can insert as many Procedures and Functions as we want. The structure of a VB program can be as follows:<br /><br />
Código: text
Formulario1 Formulario2 Formulario3 Módulo1 Modulo2<br /><br />Declaraciones Declaraciones Declaraciones Declaraciones Declaraciones<br /><br />Proc. A1 Proc.B1 Proc.C1 Proc.D1 Proc.E1<br /><br />Proc. A2 Proc.B2 Proc.C2 Proc.D2 Proc.E2<br /><br />Proc. A3 Proc.B3 Proc.C3 Proc.D3 FunciónE1<br /><br />Proc. A4 Proc.B4 Proc.C4 Proc.D4 FunciónE2<br /><br />Proc. A5 Proc.BB1 Proc.CC1 FunciónE3<br /><br />Proc. AA1 Proc.BB2 Proc.CC2 FunciónE4<br /><br />Proc. AA2 Proc.B33 Proc.CC3 FunciónE5<br /><br />Proc. AA3 Proc.CC4 FunciónE6
<br /><br />If a variable is declared inside a procedure or Function, that variable "DOES NOT LEAVE" the Procedure or Function where it was declared. The procedure can be in a Form (any procedure of a control or a procedure created by us) or in a Module (in this case, the procedure can only be created by us)<br /><br />In a Form, a variable can be declared in two ways: Private or Public. To declare a variable at form level, it must be done in the declarations section, which is in the code window Object = General, Proc. = Declarations. If it is declared Private, that variable can move throughout the whole form (that is, through all the procedures of all the controls on the form and through the Procedures we might insert in that form), but it does not leave that form. If it is declared Public, that variable can move throughout the whole form, the same way it would if declared Private, and in addition it can be used from another Form or Module, referring to it with the Form name followed by the variable name (Formulario.Variable)<br /><br />In a Module a variable can be declared as Private, so it will not leave that Module, or Public, in which case it can be used throughout the program. When a variable is declared as public in a Module, it is enough to refer to it by its name, without mentioning the name of the Module where it was declared.<br /><br />In VB it is possible to declare variables several times, that is, they can be declared at form level, in its declarations section, and that variable will keep its value in all parts of that form. However, if a variable with the same name is declared at a lower level, for example at the beginning of a procedure, that variable will be a different variable from the previous one, even though it has the same name, and since it is declared in a Procedure, it will only be valid in that Procedure. Once we have left that procedure, the variable with that name will again be the one declared in the Form. In reality, what we have are two different variables with the same name, one declared for the whole form except for the procedure where it was declared again, and another for that specific procedure.<br /><br />NOTE.- It is not advisable to declare a variable at two levels. It is much better to use another name for that variable inside the procedure where it would be declared a second time. An exception to this note is when we declare variables for a counter-type operation<br /><br />
Código: text
For I = 1 To N
<br /><br />It is practical to declare that variable I with the same name in each Procedure where it is used.<br /><br />Types of variable declaration.<br /><br />DIM statement This is the most common way to declare a variable as<br /><br />Private. It can be used in a Procedure, Function, Form or Module. The syntax is as follows:<br /><br />
Código: text
Dim nombrevariable As Integer (o el tipo que sea)
<br /><br />When declaring a variable with the DIM statement in a form, Function, procedure or module, the scope of the variable will be the one explained above for a variable declared as Private. That is, that variable does not leave the form, procedure or module where it was declared. Every time we enter the form, procedure or module, that variable will take the value zero (if numeric) or null (if string).<br /><br />PRIVATE statement This is the way to declare a variable as Private. It can<br /><br />only be used in the declarations section of a Form or Module. The syntax is as follows:<br /><br />
Código: text
Private nombrevariable As Tipovariable
<br /><br />When declaring a variable with the PRIVATE statement in a Form or Module, that variable can be used throughout that Form or Module (in all its Procedures and Functions), but NOT outside the Form or Module where it was declared.<br /><br />The Private statement cannot be used in a procedure or function.<br /><br />PUBLIC statement This is the way to declare a variable as Public. It can<br /><br />only be used in the declarations section of a Form or Module. The syntax is as follows:<br /><br />Public nombrevariable As Tipovariable<br /><br />When declaring a variable this way in the declarations section of a Module, that variable can be used anywhere in the program simply by referring to it by its name.<br /><br />If it is declared this way in the declarations section of a Form, that variable can be used throughout the program. To refer to it, if we are in the Form where it was declared, it is enough to refer to it by its name. If we are not in that Form, we will have to refer to it by the Form name, followed by the variable name, separated by a dot:<br /><br />NombreFormulario.Nombrevariable<br /><br />In a Module the Global statement can also be used instead of Public:<br /><br />GLOBAL statement Declares a variable that is valid throughout the program. The syntax is:<br /><br />Global nombrevariable As tipovariable<br /><br />The Global statement can only be used in the declarations section of a Module.<br /><br />With the Global statement the variable can be used throughout the entire program.<br /><br />STATIC statement<br /><br />As mentioned above, a variable declared in a procedure loses its value when leaving it. The worst part is that once the program re-enters that procedure, the variable will be set to zero. Fortunately, this has a solution. If we declare a variable in a procedure or function as static, that variable, although we cannot use it outside that procedure or function, will keep the value it had when we left it when we return to it. This static declaration is made with the Static instruction<br /><br />Static nombrevariable As tipovariable<br /><br />The name of a variable can be as long as we want, up to a maximum of 40 characters. In the Spanish version of VB you can even use í' and accented vowels. It makes no difference whether you use uppercase or lowercase. Don't be surprised if, for example, you declared it in uppercase and then refer to it in lowercase when writing the code, and it automatically changes to uppercase. The name of a variable must always begin with a letter.<br /><br />There is no problem with using long variables. When the program is compiled the name is not carried over, that is, it will not take up more space. Always use names that define the variable in some meaningful way. It is very useful when remembering what they are called, and above all, when redoing a program you wrote six months ago.<br /><br />Even though Visual Basic does not force you to declare variables, it is very useful to do so. This way you have control over the program. Experience will prove it to you.<br /><br />Let's summarize how to declare a variable:<br /><br />In a Procedure (the variable cannot be used outside this Procedure)<br /><br />
Código: text
Dim Variable As Tipovariable
<br /><br />In a Procedure, as permanent (the variable cannot be used outside this procedure, and within it keeps its value even if you leave and re-enter)<br /><br />Static Variable As Tipovariable<br /><br />In a Form (in its declarations section)<br /><br />As Private (can only be used in that Form)<br /><br />
Código: text
Dim Variable As Tipovariable ó
<br /><br />
Código: text
Private Variable As Tipovariable
<br /><br />As Public (can be used throughout the application)<br /><br />
Código: text
Public Variable As Tipovariable
<br /><br />In a Module<br /><br />As Private (can only be used in that Module)<br /><br />
Código: text
Dim Variable As Tipovariable
<br /><br />
Código: text
Private Variable As Tipovariable
<br /><br />As Public (can be used throughout the application)<br /><br />
Código: text
Public Variable As Tipovariable
<br /><br />
Código: text
Global Variable As Tipovariable
<br /><br />Typical mistake of a novice Visual Basic programmer<br /><br />I think this habit comes from the C language. But it doesn't work in VB. It consists of declaring several variables together on the same line:<br /><br />
Código: text
Dim Variable1, Variable2, Variable3, Variable4 As String
<br /><br />This declaration is done WRONG. Visual Basic will interpret Variable1, Variable2 and Variable3 as type Variant, and only Variable4 as type String<br /><br />The correct way to do it, if we want to declare those variables on a single line, is as follows:<br /><br />
Código: text
Dim Variable1 As String, Variable2 As String, Variable3 As String, Variable4 As String.
Alex ·
The Basic language of Visual Basic.<br /><br />That wasn't a play on words. VB uses instructions almost identical to those used by Quick Basic. However, it has added other new instructions, inherent to visual programming. Here we will study the simplest instructions and definitions, common to QB and VB.<br /><br />Conditional statements.<br /><br />We call conditional statements those that are executed if a certain condition is met. These are the statements any Basic text starts with, and this one won't be any different.<br /><br />The most used conditional statement is:<br /><br />If a condition is met Then<br /><br />Perform these instructions<br /><br />If it is not met<br /><br />Perform these other instructions<br /><br />End of statement.<br /><br />That's how easy it is to program in Basic. The thing is, this tool speaks English, and what was described above takes the form:<br /><br />
Código: text
If condición Then<br /><br />Instrucciones<br /><br />Else<br /><br />Otras instrucciones<br /><br />End If
<br /><br />In this example, the condition was that either a condition is met and it executes certain instructions, or it is not met, and it executes other different instructions. It may happen that, if the first condition is not met, a range of two or three possibilities opens up. The conditional statement would then take the form:<br /><br />
Código: text
If condición 1 Then<br /><br />Instrucciones<br /><br />ElseIf Condición 2<br /><br />Otras instrucciones<br /><br />ElseIf Condición 3<br /><br />Otro juego de instrucciones<br /><br />Else
<br /><br />Instructions to perform if conditions 1, 2 and 3 are not met.<br /><br />
Código: text
End If
<br /><br />As we said before, this is the most used type of conditional statement. There is another:<br /><br />
Código: text
Select Case
<br /><br />Its name almost defines what it is: it Selects, depending on the case, a certain set of instructions:<br /><br />
Código: text
Select Case variable ' variable es una variable que puede tomar los valores (p.e.) de 1 a 4
<br /><br />
Código: text
Case 1
<br /><br />Instructions to execute if variable = 1<br /><br />
Código: text
Case 2
<br /><br />Instructions to execute if variable = 2<br /><br />
Código: text
Case 3
<br /><br />Instructions to execute if variable = 3<br /><br />
Código: text
Case 4
<br /><br />Instructions to execute if variable = 4<br /><br />
Código: text
End Select
<br /><br />This procedure is much simpler and faster than the If Then Else statements<br /><br />seen above, when the range of choices is greater than 2.<br /><br />When what we want is to choose a value, not execute instructions as we did before, we have two other functions: Choose and Switch.<br /><br />Switch takes a series of parameters, all in pairs. The first term of each pair is the expression to evaluate. The second is the value it must return. In fact Switch is a function (we will see functions very soon)<br /><br />
Código: text
A = Switch (B=1, 5, B=2, 7, B=3, 11)
<br /><br />This instruction obtains a value for A that will depend on the value B takes among the possible values (1, 2 or 3)<br /><br />The Choose statement is almost the same; only the form changes. The same instruction as above can be done with Choose as follows:<br /><br />
Código: text
A = Choose ( B, 5, 7, 11 )
<br /><br />In these statements, Switch and Choose, if the value of B does not match any of the values that had been set (1, 2 or 3 in our case), the statement returns the value Null. This can cause an error if that possibility is not taken into account.<br /><br />With these conditional statements it is possible to branch the program, change the properties of an object, obtain results of operations, ....<br /><br />Loop statements.<br /><br />It is very common to use loops throughout a program. A loop is a repetitive succession of instructions, which will keep being executed while a condition is met or while another condition is not met. It's as simple as this:<br /><br />While condition<br /><br />Instructions<br /><br />End of loop<br /><br />There are two forms of loop: one that goes through the loop a set number of times. This is the so-called counter loop. The other performs the loop until a condition is met (or stops being met). This is the so-called condition loop.<br /><br />Counter loop<br /><br />It performs the loop as many times as we tell it. For example, this loop will display the 26 uppercase letters of the English alphabet<br /><br />
Código: text
For N=65 To 90<br /><br />Label1.caption = Chr ( N )<br /><br />Next N
<br /><br />This "program" will display in a box (Label) the characters whose ASCII number goes from 65 (A) to 90 (Z). It will start by displaying the one corresponding to number 65, and will successively display 66, 67, etc., until it reaches 90, where it will stop.<br /><br />Condition loops<br /><br />It executes the loop instructions while a condition is met<br /><br />
Código: text
X = 0<br /><br />Do While X < 1000<br /><br />X = X + 1<br /><br />Loop
<br /><br />The program takes a variable (X) that we previously took care to set to zero, and increments its value by one. It checks whether the value of X is less than 1000, and if true, it runs the loop again. And so on until X is no longer less than 1000. When X is no longer less than 1000, it exits the loop. We have just made a timer, and also presented conditional statements and loops, the start of any Basic course. As the end of the lesson, a problem is proposed. With the first loop, where we displayed the characters A to Z, we probably wouldn't have time to see each of the letters appearing on the screen, in the Label1 label, since it would change very fast, and we would only see the Z, which is where the program stopped. We can add a timer each time it displays a letter, so we'll have time to see it. With the two loops seen above we can already do it.<br /><br />If what we want is for the program to run while a certain condition is not met, the statement will be:<br /><br />
Código: text
X = 0<br /><br />Do Until X > 1000<br /><br />X = X + 1<br /><br />Loop
<br /><br />Notice that the difference between one and the other is the condition: While to indicate While it is true that ... and Until to indicate While it is not true that ....<br /><br />To properly finish the previous program we will use the While condition (While the condition is met)<br /><br />
Código: text
For N=65 To 90<br /><br />Label1.caption = Chr ( N )<br /><br />Label1.RefreshN ' Refresca la etiqueta<br /><br />X = 0<br /><br />Do While X < 1000<br /><br />X = X + 1<br /><br />Loop<br /><br />Next N
<br /><br />This is our first program in BASIC. In VISUAL BASIC it is identical, but we're missing the graphical interface. To make it, just open VB and on the form that appears when opening it, add a label (Label), which will have the default name Label1. All that remains is to think about where to put the code above. We can add a command button (Command Button), which will appear with the default name Command1. Double-click on the button. The Click procedure will appear. This procedure is the one executed when we click on that button. Write this code in that procedure.<br /><br />
Código: text
Private Sub Command1_Click() ' Esta línea sale automáticamente<br /><br />For N=65 To 90<br /><br />Label1.caption = Chr ( N )<br /><br />Label1.RefreshN ' Refresca la etiqueta<br /><br />X = 0<br /><br />Do While X < 1000 ' Bucle de temporización<br /><br />X = X + 1<br /><br />Loop<br /><br />Next N ' Termina el bucle de temporización<br /><br />End Sub ' Esta línea sale automáticamente
<br /><br />We have laid our first stone in Visual Basic. This example is very simple. Visual Basic is as simple as this example.
Alex ·
<br />VISUAL BASIC BASICS CH. 2<br /><br />___________________________<br /><br />String functions<br /><br />A STRING is a sequence of characters. A string can have one or more alphanumeric characters. A string is also a sequence of numbers.<br /><br />Examples of strings:<br /><br />Curso de Visual Basic<br /><br />abcdefghijklmnopqrstuvwxyz1234567890<br /><br />123456789<br /><br />Let's make a distinction between a string containing numbers and a number. A number has a value, but it also has a written representation. The value is something that will be in the computer as a sequence of bits. Depending on how we declared it, it will have more or fewer bits. But that information is not a number readable by the user. What is readable by the user is the representation in decimal notation (or octal, or hexadecimal, or even binary) of that number. That representation of the number in a given numbering system is a string.<br /><br />Thus, the number nine, which in the computer's memory will be a sequence of bits, the computer can present to us as:<br /><br />9 In decimal notation<br /><br />9 In hexadecimal notation<br /><br />11 In octal notation<br /><br />1001 In binary notation<br /><br />Those ways of presenting the number are character STRINGS. The value of the number inside the computer is a NUMBER.<br /><br />To display a number on the screen, the computer must first convert it to a string.<br /><br />When we enter a numeric value via the keyboard or screen, the computer, in order to perform operations with it, must transform it into a number.<br /><br />These considerations lead us to the first two string functions:<br /><br />Str (number) Converts a number to a string in decimal notation.<br /><br />Val (numeric string) Obtains the value (the number) corresponding to that string.<br /><br />Examples<br /><br />
Código: text
Variablenumerica = Val (TextBox1.Text)
<br /><br />This example converts the string of (numeric) characters in the text box TextBox1 into a number, and assigns this number to the variable Variablenumerica.<br /><br />If the content of the text box were not numeric characters (abcd, for example), Variablenumerica would take the value 0.<br /><br />
Código: text
Label1.Caption = Str (Variablenumerica)
<br /><br />This example would put in the label Label1 the characters corresponding to the value of the variable Variablenumerica.<br /><br />Note to remember: You will always have to convert a number to a string when you want to display it on screen. You will always have to convert to a number the string of numeric characters entered via keyboard or screen when you want to operate with that number. A Label, when it has to display a single number, will not ask you to convert it to a string, since VB does that conversion automatically. However, when it has to display a number and also text in the same Label, VB will not perform that conversion automatically, so it will give you an error. I recommend converting numbers to string variables whenever you want to display them in a Label or TextBox.<br /><br />There is a broader function than Str. It is Cstr. This function not only transforms a number into a string, as Str does, but converts any type of variable into a String variable.<br /><br />This function transforms, for example, a Boolean variable into a string variable, returning the string "Verdadero" (True) if the value of the boolean variable is True, and "Falso" (False) if it is False.<br /><br />It can also transform the value of a CheckBox or an OptionButton into a character string. In these cases it returns 0 and 1 for the CheckBox (Unchecked / Checked) and Verdadero or Falso for the OptionButton (Selected / Unselected)<br /><br />
Código: text
label1.Caption = CStr(booleana) Label1.Caption = Verdadero si booleana es true<br /><br />Label1.Caption = Falso si booleana es False<br /><br />Label2 = CStr(Check1.Value) Label2.Caption = 1 si Check1 está activado<br /><br />Label2.Caption = 0 si Check1 está desactivado<br /><br />Label3 = CStr(Option1.Value) Label3.Caption = Verdadero si Check1 está activado<br /><br />Label3.Caption = Falso si Check1 está desactivado
<br /><br />If Cstr is applied to a Date/Time variable, it returns the date / time in short format.<br /><br />More string functions:<br /><br />Left (cadena, n)<br />Extracts the first n characters of a string, starting from the left.<br /><br />If cadena = Curso de Visual Basic (for all examples)<br /><br />Resultado = Left (cadena, 10) ----> Resultado = Curso de V<br /><br />Right (cadena, n) Extracts the last n characters of the string<br /><br />Resultado = Right (cadena, 10) ----> Resultado = sual Basic<br /><br />Mid (cadena, m, n) Extracts n characters from the string, the first extracted character being the one in position m.<br />(See Mid Instruction below)<br /><br />Resultado = Mid (cadena, 3, 10) ----> Resultado = rso de Vis<br />L<br /><br />Case (cadena) Returns an identical string, but with all<br /><br />characters in lowercase. (LCase = Lower Case)<br /><br />Resultado = Lcase (cadena) ----> Resultado = curso de visual basic<br /><br />UCase (cadena) Returns an identical string, but with all<br /><br />characters in uppercase. (UCase = Upper Case)<br /><br />Resultado = UCase (cadena) ----> Resultado = CURSO DE VISUAL BASIC<br /><br />Len (cadena) Returns the length of the string<br /><br />Resultado = Len (cadena) ----> Resultado = 21<br /><br />LenB (Cadena) Returns the number of Bytes used to store the<br /><br />string. Surprise, it's double Len (Cadena)<br /><br />String (n, carácter) Returns a string of n characters like the one indicated<br /><br />Resultado = String (8, "a") ----> Resultado = aaaaaaaa<br /><br />Resultado = String (8, Chr(65)) ----> Resultado = AAAAAAAA<br /><br />Resultado = String (8, 65) ----> Resultado = AAAAAAAA<br /><br />Space (n) Returns a string made up of n spaces.<br /><br />Resultado = "A" + Space (6)+ "B" ----> Resultado = A B<br /><br />LTrim Removes any spaces a string may have on its left.<br /><br />Rtrim Removes any spaces a string may have on its right.<br /><br />Trim Removes the spaces a string has, both on its left and on its right. (It does not remove the spaces<br /><br />in the middle of the string)<br /><br />These three functions are used to remove possible spaces that may result from data entry. They are especially important when data is taken from a file or database, where it was entered by another program.<br /><br />No example of these functions is given, as it would be hard to see it in print.<br /><br />InStr (cadena, cadena1) Searches for cadena1 within cadena and returns the position within cadena where the first letter of cadena1 is found<br /><br />
Código: text
Resultado = InStr (cadena, "sua") ----> Resultado = 12
<br /><br />StrConv Converts a character string into another, according to the instructions<br /><br />that follow it. It can replace UCase or LCase if the instruction is<br /><br />UpperCase or LowerCase respectively, or capitalize the first letter of every word in the string if the instruction is ProperCase.<br /><br />
Código: text
Resultado = StrConv (cadena, UpperCase) ----> Resultado = CURSO DE VISUAL BASIC<br /><br />Resultado = StrConv (cadena, LowerCase) ----> Resultado = curso de visual basic<br /><br />Resultado = StrConv (cadena, ProperCase) ----> Resultado = Curso De Visual Basic
<br /><br />Mid Instruction<br /><br />Mid can also be used to change the content of a string. Note the subtlety between Mid as a string Function and Mid as an Instruction.<br /><br />The Mid Instruction replaces a specified number of characters in a string variable with characters from another string.<br /><br />
Código: text
Sintaxis Mid(cadena1, inicio[, longitud]) = cadena2
<br /><br />
Código: text
Resultado Mid (cadena, 7,2)="Sobre" ---- > Resultado = Curso sobre Visual
Alex ·
Basic FUNCTIONS WITH NUMBERS CH. 3<br />_________________________<br /><br />Visual Basic can operate with numbers just like any person would. It knows the 4 basic operations, and can use parentheses the same way we write them on paper.<br /><br />The operators it uses for basic operations are:<br /><br />+ Addition<br /><br />- Subtraction<br /><br />* Multiplication<br /><br />/ Division<br /><br />\ Division without decimals<br /><br />Mod Remainder of a division<br /><br />^ Raises to an exponent<br /><br />Examples<br /><br />Resultado = 12 + 15 ----> Resultado = 27<br /><br />Resultado = 15 - 12 ----> Resultado = 3<br /><br />Resultado = 15 * 12 ----> Resultado = 180<br /><br />Resultado = 15 / 12 ----> Resultado = 1.25<br /><br />Resultado = 15 \ 12 ----> Resultado = 1<br /><br />Resultado = 15 Mod 12 ----> resultado = 3<br /><br />Resultado = 12 ^ 2 ----> Resultado = 144<br /><br />resultado = ( ( 4 * 3 ) / 2 ) ^ 2 ----> Resultado = 36<br /><br />These operators are called Arithmetic operators.<br /><br />There are other operations that can be performed with numbers: comparisons. The operators that perform comparisons are called Relational operators. Operations performed with these operators only allow two results: True or False. These operators are:<br /><br />= Equal to<br /><br /><> Not equal to<br /><br />< Greater than<br /><br /><= Greater than or equal to<br /><br />> Less than<br /><br />=> Equal to or less than<br /><br />These operators are usually used in program structures where a decision is made.<br /><br />The = operator can also be used to compare strings or dates.<br /><br />Logical Operators<br /><br />These operators only make sense when we talk about Boolean variables, that is, those that can only take the values zero and one.<br /><br />Operator Function Returns True if Returns False if<br /><br />And AND function A=True and B=True Any other case<br /><br />Or OR function A=True or B=True A=False and B=False<br /><br />Xor XOR function A=True and B=False A=True and B=True<br /><br />A=False and B=True A=False and B=False<br /><br />Eqv Equivalence F. A=True and B=True A=True and B=False<br /><br />A=False and B=False A=False and B=True<br /><br />Imp Implication A=True and B=True A=True and B=False<br /><br />A=False and B=True<br /><br />A=False and B=False<br /><br />Not Negation A=False A=True<br /><br />Like Equality A=True A=False<br /><br />Other Functions with numbers<br /><br />CInt Integer part Returns the integer part of a number with decimals<br /><br />Abs Absolute value Returns the absolute value of a number<br /><br />Sgn Sign Returns the sign of a number<br /><br />Sqr Square root Returns the square root of a number<br /><br />Exp Exponentiation Returns the number raised to the indicated exponent<br /><br />Log Logarithm Returns the natural logarithm of that number<br /><br />Trigonometric<br /><br />Sin Sine Returns the value of the sine of an angle (expressed<br /><br />in radians)<br /><br />Cos Cosine Returns the cosine of an angle (in radians)<br /><br />Tan Tangent Returns the tangent of an angle<br /><br />Atn Arc Tan. Returns an arc whose tangent is the number<br /><br />(angle in radians)<br /><br />A curious function<br /><br />Timer Accumulated time Returns the time (in seconds) that has passed since midnight.<br /><br />Random number generation<br /><br />Randomize (Numero) Starts the random generator taking Numero as the starting value. It returns the result in a variable called Rnd.<br /><br />VERY IMPORTANT NOTE.- Random numbers generated this way are always the same, depending, of course, on the number passed as a parameter. This number generation does not produce random numbers because, as stated, they depend on the number passed as the parameter, and if it repeats, the sequence of numbers created by the random generator repeats.<br /><br />The way to get truly random numbers is to pass as a parameter a number that varies with time.
Alex ·
Option Base 1<br /><br />which must be placed at the beginning of the module or form where we declare the array.<br /><br />To declare the array, it is done as with all variables, specifying in parentheses the number of elements that make up the array:<br /><br />
Código: text
Dim Alumno (25) as String
<br /><br />We have declared that the variable alumno is a string, and that there are 25 elements in that array.<br /><br />An array can also be declared as follows:<br /><br />
Código: text
Dim Alumno(1 To 25) as String
<br /><br />Where we tell it that the variable Alumno has 25 elements, that the first one has index 1 and the last one has index 25.<br /><br />But let's imagine we want to put the student's first name, first surname and second surname in the same array. We will need to declare a 25 by 3 array. Since all the elements will be character strings, we can declare it as follows:<br /><br />
Código: text
Dim Alumno (1 To 25, 1 To 3) As String
<br /><br />This way, the first surname of the student in position number 15 of the class will be the element:<br /><br />Alumno (15, 2)<br /><br />We can define arrays with more than two dimensions. We can reach a maximum of 60 dimensions. A 5-dimensional array would be declared:<br /><br />
Código: text
Dim Variable ( 1 To N, 1 To M, 1 To P, 1 To Q, 1 To R)
<br /><br />meaning that there are N, M, P, Q and R elements in each of the dimensions respectively.<br /><br />A variable already declared as an array can be resized during the program with the ReDim instruction<br /><br />
Código: text
ReDim Alumno (1To 25)
<br /><br />With this instruction, we are ReDimensioning an already declared array. A non-existent array cannot be resized.<br /><br />With the declaration 1 To 25 we are telling it that the first element of the array is 1, regardless of what we put in OPTION BASE. If it is resized simply with the number of elements:<br /><br />
Código: text
ReDim (25)
<br /><br />we are telling it that it has 25 elements, but whether the first is 0 or 1 depends on having set OPTION BASE 0 or OPTION BASE 1.<br /><br />An array can be resized as many times as you want throughout the application, but that resizing cannot affect the number of dimensions of the array. If we resize the array it will lose the existing information. To avoid losing the information in the array, you must use the ReDim Preserve statement.<br /><br />If you use the Preserve keyword on arrays with more than 1 dimension, you will run into unexpected behavior. As you can see in the VB Help, using ReDim Preserve you can only change the size of the last dimension of the array and you can never modify the number of dimensions. That is NOT entirely true. You can do it once.<br /><br />Regarding changing the number of dimensions, if you declared the array with specific dimensions, you can no longer change the dimensions with either ReDim or ReDim Preserve. You will get an error saying that the array dimensions have already been declared.<br /><br />But if you declared the array without dimensions:<br /><br />
Código: text
Dim MiMatriz()
<br /><br />you can change the dimensions Dim MiMatriz (1 To 5, 1 To 9)<br /><br />and change them again Dim MiMatriz (1 To 8, 1 To 15, 1 To 6)<br /><br />Note that not only have we changed its dimensions twice (first to 2 and then to 3), but we have also changed the number of elements in each dimension.<br /><br />If we had used ReDim Preserve we could only have used the first of the two lines above:<br /><br />
Código: text
ReDim Preserve MiMatriz (1 To 5, 1 To 9)
<br /><br />but we could no longer change the number of dimensions again with the second line. It would give us an error.<br /><br />With ReDim we can change the number of elements in each dimension as many times as we want. For example, we can resize MiMatriz as follows:<br /><br />
Código: text
ReDim MiMatriz (1 To 5, 1 To 9)<br /><br />ReDim MiMatriz (1 To 15, 1 To 20)<br /><br />ReDim MiMatriz (1 To 25, 1 To 30)
<br />. . . . . . . . . . . . . . . . . . . . . . . . . . .<br /><br />If we had used ReDim Preserve, we could change the elements of all the dimensions of the array once:<br /><br />
Código: text
ReDim Preserve (1 To 5, 1 To 9)
<br /><br />from then on, we can only change the elements of the last dimension:<br /><br />
Código: text
ReDim Preserve (1 To 5, 1 To 20)<br /><br />ReDim Preserve (1 To 5, 1 To 30)
<br /><br />that is, we cannot do this:<br /><br />ReDim Preserve (1 To 10, 1 To 30) where the error is marked in bold.<br /><br />This does not cause any error in a one-dimensional array, since if the array has only one dimension, you can change the size of that dimension because it is the only and the last one.<br /><br />When an array keeps being resized throughout the application, we may reach the situation where, at a given moment, we don't know the dimensions of that array.<br /><br />To know the maximum and minimum index of an array, the UBound and LBound functions are used.<br /><br />UBound returns the largest subscript available for the indicated dimension of an array.<br /><br />
Código: text
Sintaxis UBound(nombredelamatriz[, dimensión])
<br /><br />LBound returns the largest subscript available for the indicated dimension of an array.<br /><br />
Código: text
Sintaxis LBound(nombredelamatriz[, dimensión])
<br /><br />Example Let's have an array called Mimatriz, with three dimensions. At some point in the application the following valid instruction was executed:<br /><br />
Código: text
ReDim Mimatriz (1 To 100, 0 To 3, 5 To 20)
<br /><br />At another point we want to keep track of the indices of that array, and we want to find out the lowest and highest index of each of its dimensions:<br /><br />
Código: text
(IID1= Indice Inferior Dimensión 1, ISD 1 = Indice Superior Dimensión 1, etc. )<br /><br />IID 1= LBound (Mimatriz, 1) IID1 = 1<br /><br />ISD1 = UBound (Mimatriz, 1) ISD1 = 100<br /><br />IID 2= LBound (Mimatriz, 2) IID1 = 0<br /><br />ISD2 = UBound (Mimatriz, 2) ISD1 = 3<br /><br />IID 1= LBound (Mimatriz, 3) IID1 = 5<br /><br />ISD1 = UBound (Mimatriz, 3) ISD1 = 20<br />
gouldyas ·
Very good guide... interesting for those who are starting out
Grupo de WhatsApp