This action might not be possible to undo. Are you sure you want to continue?
What is Visual Basic? •The "Visual" part refers to the method used to create the graphical user interface (GUI). Rather than writing numerous lines of code to describe the appearance and location of interface elements, you simply add pre-built objects into place on screen •The "Basic" part refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code) language
Visual Basic Characteristics • Rapid Application Development (RAD) tool • Front-end applications. •ActiveX technologies allow you to use the functionality provided by other applications, such as Microsoft Word word processor, Microsoft Excel spreadsheet, and other Windows applications. •Your finished application is a true .exe file.
Event-Driven programming Language? In an event-driven application, the code doesn't follow a predetermined path — it executes different code sections in response to events. Events can be triggered by the user's actions, by messages from the system or other applications, or even from the application itself. The sequence of these events determines the sequence in which the code executes, thus the path through the application's code differs each time the program runs. Your code can also trigger events during execution. For example, programmatically changing the text in a text box cause the text box's Change event to occur.
Interactive Development The traditional application development process can be broken into three distinct steps: writing, compiling, and testing code. Unlike traditional languages, Visual Basic uses an interactive approach to development, blurring the distinction between the three steps. With most languages, if you make a mistake in writing your code, the error is caught by the compiler when you start to compile your application. You must then find and fix the error and begin the compile cycle again, repeating the process for each error found. Visual Basic interprets your code as you enter it, catching and highlighting most syntax or spelling errors on the fly.
In addition to catching errors on the fly, Visual Basic also partially compiles the code as it is entered. If the compiler finds an error, it is highlighted in your code. You can fix the error and continue compiling without having to start over. Because of the interactive nature of Visual Basic, you'll find yourself running your application frequently as you develop it. This way you can test the effects of your code as you work rather than waiting to compile later.
The Integrated Development Environment Selecting the Project Type
Working with Visual Basic Projects A project consists of : •One project file that keeps track of all the components (.vbp). •One file for each form (.frm). •One binary data file for each form containing data for properties of controls on the form (.frx). These files are not editable and are automatically generated for any .frm file that contains binary properties, such as Picture or Icon. •Optionally, one file for each class module (.cls). •Optionally, one file for each standard module (.bas). The project file is simply a list of all the files and objects associated with the project, as well as information on the environment options you set. You can convert the project into an executable file (.exe)
Form Modules Form modules (.frm file name extension) can contain textual descriptions of the form and its controls, including their property settings. They also contain form-level declarations of constants, variables and procedures; event procedures; and general procedures. Class Modules Class modules (.cls file name extension) are similar to form modules, except that they have no visible user interface. You can use class modules to create your own objects, including code for methods and properties. Standard Modules Standard modules (.bas file name extension) can contain public or module-level declarations of types, constants, variables, external procedures, and public procedures.
Variable is a placeholder in memory. Variables are used to temporarily store values during the execution of an application. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store). A variable name: •Must begin with a letter. •Can't contain an embedded period. •Must not exceed 255 characters. •Must be unique within the same scope, which is the range from which the variable can be referenced — a procedure, a form, and so on.
Implicit Declaration You don't have to declare a variable before using it. Visual Basic automatically creates a variable with that name, which you can use as if you had explicitly declared it. While this is convenient, it can lead to subtle errors in your code if you misspell a variable name. Example: x = “Sam” a = 45 Explicit Declaration To avoid the problem of misnaming variables, you can stipulate that Visual Basic always warn you whenever it encounters a name not declared explicitly as a variable. Place this statement in the Declarations section of a class, form, or
Scope of Variables A variable is scoped as either a procedure-level (local) or modulelevel variable. Scope Procedure-level Private: Variables are private to the procedure in which they appear. Public: Not applicable. You cannot declare public variables within a procedure. Module-level Private: Variables are private to the module in which they appear. Public: Variables are available to all modules.
The Variant Data Type Variant variables can hold any type of data described so far, and then some. Variables of this type take 16 bytes, in this format:
Bytes 0 and 1 hold an integer value that states which type of data is stored in bytes 8 through 15. Bytes 2 through 7 are unused (with only one exception, the Decimal subtype), and in most cases not all the bytes in the second half of the variable are used. For example, if a Variant holds an Integer value, the first two bytes contain the value 2-vbInteger, bytes 8 and 9 hold the actual 16-bit value, and all other bytes are unused.
Variables Used Within a Procedure You declare them with the Dim or Static keywords. For example: Dim intTemp As Integer or Static intPermanent As Integer Variables Used Within a Module You create module-level variables by declaring them with the Private keyword in the Declarations section at the top of the module. Private intTemp As Integer At the module level, there is no difference between Private and Dim, but Private is preferred because it readily contrasts with Public and makes your code easier
Variables Used by All Modules To make a module-level variable available to other modules, use the Public keyword to declare the variable. The values in public variables are available to all procedures in your application. Like all module-level variables, Public variables are declared in the Declarations section at the top of the module. Public intTemp As Integer
The syntax for declaring a constant is: [Public|Private] Const constantname[As type] = expression A Const statement can represent a mathematical or date/time quantity: Const conPi = 3.14159 Public Const conMaxPlanets As Integer = 9 Const conReleaseDate = #1/1/95# Const conCodeName = "Enigma" You can place more than one constant declaration on a single line if you separate them with commas: Public Const conPi = 3.14, conMaxPlanets = 9
Data Types By default, if you don't supply a data type, the variable is given the Variant data type. The Variant data type can represent many different data types in different situations. Declaring Variables with Data Types You must use Private, Public, Dim or Static statement to declare it As type. Numeric Data Types Visual Basic supplies several numeric data types — Byte, Integer, Long Single (single-precision floating point), Double (double-precision floating point), and Currency.
The String Data Type Private S As String S = "Database" You specify a fixed-length string with this syntax: String * size For example, to declare a string that is always 50 characters long, use code like this: Dim EmpName As String * 50 The Boolean Data Type If you have a variable that will contain simple true/false The default value of Boolean is False. Dim blnRunning As Boolean
The Date Data Type Date and time values can be contained both in the specific Date data type and in Variant variables.
The Object Data Type Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an application or within some other application. A variable declared as Object is one that can subsequently be assigned (using the Set statement) to refer to any actual object recognized by the application.
Converting Data Types Conversion functions to convert values into a specific data type. Conversion function Cbool Cbyte Ccur Cdate CDbl Cint CLng CSng CStr Cvar Converts an expression to Boolean Byte Currency Date Double Integer Long Single String Variant
Arrays Fixed-Size Arrays When declaring an array, follow the array name by the upper bound in parentheses. The upper bound cannot exceed the range of a Long data type (-2,147,483,648 to 2,147,483,647). For example Dim Counters(14) As Integer elements. ' 15
To specify a lower bound, provide it explicitly using the To keyword: Dim Sums(100 To 120) As String
Multidimensional Arrays Dim MatrixA(9, 9) As Double Either or both dimensions can be declared with explicit lower bounds: Dim MatrixA(1 To 10, 1 To 10) As Double
Dynamic Arrays A dynamic array can be resized at any time. To create a dynamic array • • Declare the array as dynamic by giving it an empty dimension list.Dim DynArray() Allocate the actual number of elements with a ReDim statement.ReDim DynArray(X + 1) The ReDim statement can appear only in a procedure. Unlike the Dim and Static statements, ReDim is an executable statement — it makes the application carry out an action at run time. Each ReDim can change the number of elements, as well as the lower and upper bounds. ReDim DynArray(4 to 12)
Preserving the Contents of Dynamic Arrays Each time you execute the ReDim statement, all the values currently stored in the array are lost. Sometimes you may want to change the size of the array without losing the data in the array. You can do this by using ReDim with the Preserve keyword. ReDim Preserve DynArray(UBound(DynArray) + 1)
User-Defined Types A user-defined type (UDT) is a compound data structure that holds several variables of simpler data types. Before you can use a UDT variable, you must first define its structure, using a Type directive in the declaration section of a module:
Private Type EmployeeUDT Name As String Department ID As Long Salary As Double End Type The Type statement can be used only at module
Private Type EmployeeRecord ' Create user-defined type. ID As Integer ' Define elements of data type. Name As String * 20 Address As String * 30 Phone As Long End Type Private Sub Form_Load() Dim MyRecord As EmployeeRecord ' Declare variable. ' Assignment to EmployeeRecord variable must occur in a procedure. MyRecord.ID = 12003 MsgBox MyRecord.ID End Sub
Mathematical Operators Operator +, + * / ^ Meaning Unary positive, negative Addition Subtraction Multiplication Division exponentiation
Interestingly, the division operator (/) always converts both its operands to Double, which can cause some unexpected overhead. If you're dividing an Integer or Long number by another Integer or Long number and you aren't interested in the decimal part of the quotient, you should use the integer division operator (\), which executes faster:
Comparison Operators Visual Basic supports six comparison operators, which can be applied to both numeric and string operands: = < <= > >= <>
Boolean Visual Basic for Applications supports a few Boolean operators, which are especially useful for combining multiple Boolean subexpressions. The operators used most frequently are AND, OR, XOR, and NOT.
Rounding and Truncating The Int function truncates a number to the integer value equal or lower than its argument. Print Int(1.2) ' Displays "1" Print Int(-1.2) ' Displays "-2" The function that actually truncates the decimal part of a number is Fix: Print Fix(1.2) ' Displays "1“ Print Fix(-1.2) ' Displays "-1" Round, which lets you round a decimal number to the number of digits you want (or to the nearest integer, if the second argument is omitted): Print Round(1.45) ' Displays "1" Print Round(1.55) ' Displays "2"
Round cont….. When the fractional part is exactly 0.5, it rounds up if the integer portion is an odd number and rounds down if it's even: Print Round(1.5), Round(2.5) ' Both display "2".
Breaking a Single Statement Into Multiple Lines You can break a long statement into multiple lines in the Code window using the line-continuation character (a space followed by an underscore). Using this character can make your code easier to read, both online and when printed. S= _ "SELECT * FROM Titles, Publishers" _ & "WHERE Publishers.PubId = Titles.PubID" _ & "AND Publishers.State = 'CA'" You can't follow a line-continuation character with a comment on the same line.
Combining Statements on One Line You can place two or more statements on a line if you use a colon (:) to separate them: Text1.Text = "Hello" : Red = 255 In order to make your code more readable, however, it's better to place each statement on a separate line.
Adding Comments to Your Code As you read through the examples in this guide, you'll often come across the comment symbol ('). This symbol tells Visual Basic to ignore the words that follow it.
These can be of type Sub or Function, depending on whether they return a value to the caller. Each procedure has a unique name, a scope, a list of expected arguments, and—if it's a function—a return value. Scope can be Private, Public, or Friend. A Private procedure can be invoked only from within the module in which it's defined. A Public procedure can be invoked from outside the module. A Friend procedure is halfway between Private and Public: Such a procedure can be called from anywhere in the current project, but not from outside it. This difference becomes important only if you're within a project of a type other than Standard EXE, one that therefore exposes its classes to other applications in the form of COM components.
Control Flow If...Then If condition Then statement If condition Then statements End If
If...Then...Else If condition1 Then [statementblock-1] [ElseIf condition2 Then [statementblock-2]] ... [Else [statementblock-n]] End If
' Single line version, without Else clause If x > 0 Then y = x ' Single line version, with Else clause If x > 0 Then y = x Else y = 0 ' Single line, but with multiple statements separated by colons If x > 0 Then y = x: x = 0 Else y = 0
' Multiline version of the above code (more readable) If x > 0 Then y=x x=0 Else y=0 End If ' An example of If..ElseIf..Else block If x > 0 Then y=x ElseIf x < 0 Then y=x*x Else ' X is surely 0, no need to actually test it. x = -1 End If
Select Case A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more readable when there are several choices. Select Case testexpression [Case expressionlist1 [statementblock-1]] [Case expressionlist2 [statementblock-2]] . . . [Case Else [statementblock-n]] End Select
The Select Case statement is less versatile than the If block in that it can test only one expression against a list of values: Select Case Mid$(Text, i, 1) Case "0" To "9" ' It's a digit. Case "A" To "Z", "a" To "z" ' It's a letter. Case ".", ",", " ", ";", ":", "?" ' It's a punctuation symbol or a space. Case Else ' It's something else. End Select
Loop Structures Do While condition statements Loop Do statements Loop While condition Do statements Loop Until condition While condition [statements] Wend
For...Next The syntax is: For counter = start To end [Step increment] statements Next [counter] The arguments counter, start, end, and increment are all numeric.
For Each...Next Syntax : For Each element In group statements Next element
IIf Function Returns one of two parts, depending on the evaluation of an expression. Syntax IIf (expr, truepart, falsepart) expr. Expression you want to evaluate. truepart. Value or expression returned if expr is True. falsepart. Value or expression returned if expr is False. IIf always evaluates both truepart and falsepart, even though it returns only one of them. Because of this, you should watch for undesirable side effects. For example, if evaluating falsepart results in a division by zero error, an error occurs even if expr is True.
With Statement Executes a series of statements on a single object or a user defined type. Syntax With object [statements] End With Example: With MyObject .Height = 100 ' Same as MyObject.Height = 100. .Caption = "Hello" ' Same as MyObject.Caption = "Hello". With .Font Red. True. .Color = Red ' Same as MyObject.Font.Color = .Bold = True ' Same as MyObject.Font.Bold =
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.