Home
About me



 VBA Programming
Download my Add-In tool (run on 32-bit MS Office Excel)
VBA Basic for beginners
Excel Main Objects
More with Rows, Columns, Cells, Range ...
Working around your Worksheet ...
Statements
Functions
Conditional Statements and Loops Structure
Errors Handling
UserForms
Pivot Tables
Charting
AutoFilter, Advanced Filter
File I/O VBA Examples
ADO and DAO, integrating Excel and Access
Other VBA fun staff
 

Excel VBA Statements

A statement in Visual Basic is a complete instruction that make declaration, defines an action, defines an item, or gives the value of a variable. It can contain keywords, operators, variables, constants, and expressions. A statement usually fits on one line, but you can continue a statement onto the next line using a line-continuation character, which is the combination of a space followed by an underscore. Visual Basic ignores comments when it runs your procedures. Comment lines begin with an apostrophe ( ' ) or with Rem followed by a space, and can be added anywhere in a procedure. Each statement belongs to one of the following three categories:

  • Declaration statements, which name a variable, constant, or procedure and can also specify a data type.
  • Assignment statements, which assign a value or expression to a variable or constant.
  • Executable statements, which initiate actions. These statements can execute a method or function, and they can loop or branch through blocks of code. Executable statements often contain mathematical or conditional operators.


Declaration Statements

Option Explicit Public
Option Private Private
Option Compare Friend
Declare Set
Sub Let
Function ArrayName
Const Enum
Dim VarType
ReDim DefType...


Assignment Statements

= Operator * Operator XOR Operator
^= Operator / Operator NOT Operator
*= Operator \ Operator EQV Operator
/= Operator ^ Operator IMP Operator
\= Operator () Operator IS Operator
+= Operator & Operator LIKE Operator
-= Operator > Operator MOD Operator
<<= Operator < Operator  
>>= Operator <> Operator  
+ Operator AND Operator  
- Operator OR Operator  


Executable Statements

If..Then..Else IIF GoSub
For...Next Choose On…GoSub
For Each ... Next With…End With On…GoTo
While...Wend Stop  
Select Case - End Select Watch  
Do...Loop GoTo  

 

Declaration Statements

Before you can use a variable, you must first declare it. When you declare a variable, you are:
   instructing your computer which parts of your program have permission to store and retrieve data in a variable
   telling your computer the name of your variable
   defining the data type that your variable can hold

You use declaration statements to name and define procedures, variables, properties, arrays, constants, and also define its data type, access level, and scope. When the code that contains your declaration statement runs, Visual Basic reserves the memory required for the declared variable. If the variable holds a value, Visual Basic initializes it to the default value for its data type.  In VB.Net as the following example shows, you can assign an initial value to a variable as part of its declaration as compared to VB 6 which you have to assign a value to the variable on a second line. Note that the initial value 256 you specify in a declaration statement is not assigned to a variable until execution reaches its declaration statement. Until that time, the variable contains the default value for its data type.

' In VB 6,  declaration creates variable Lng and assign value to it in the assignment statement
Dim Lng As Long
Lng = 256

' In VB.NET, declaration creates variable Lng and assigns a value 256 to it as part of its declaration
Dim Lng As Long = 256

 

Option Explicit statement

Option Explicit is used at module-level to force explicit declaration of all variables in that module. In another word, this compiler option tells the compiler that you have to declare each variable in your before you can use it in an assignment statement. Option Explicit is usually the preferred practice and helps prevent runtime errors.

Option Explicit statement must appear in a module before any procedures. When Option Explicit appears in a module, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static statements. If you attempt to use an undeclared variable name, an error occurs at compile time. If you don't use the Option Explicit statement, all undeclared variables are of Variant type which means VBA would have to spend more time checking the data type of the variable each time it encounters it, and your code will execute longer. Worse still, you risk unintentionally storing the wrong data type in the variable. The example below declares ‘var1’ as integer type.

Option Explicit         ' forcing explicit variable declaration
Dim var1 As Integer     ' declare variable ‘var1’ as Integer data type
int1 = 10               ' undeclared variable ‘int1’ generates run-time error
var1 = 20               ' declared variable ‘var1’ won’t generate compile error

Let’s refresh on the scope of declaration. Note that a variable declared as Public is visible to all procedures in all modules in a directly referencing project unless Option Private Module is in effect. When Option Private Module is in effect, the module itself is private and therefore not visible to referencing projects. Variables declared in a Option Private Module procedure are accessible only within the procedure and lose their value between calls unless they are declared Static. Variables declared with the Static statement retain their values as long as the code is running until the module is reset or restarted.
 


Option Private Module statement
This option marks the code in the module as private so that it can’t be seen by users in the macros dialog box. It also prevents the module's contents (that is, variables and objects) from referenced by external projects. Subroutines in private module won’t appear in Excel when you choose Tools>Macro>Macros. They will still be available to other modules within the same project provided the procedures in the option private module are not individually declared as Private. Option Private is only necessary when working with host applications that allow variables and objects to be referenced across multiple projects.

Option Explicit
Option Private Module
      ' indicates that the module is private

You need to use Option Private Module as the first line in the module (above and outside of any variable declaration or procedure). This option makes everything in the module accessible only from within the project. The project variables that should not be accessible to other projects should be declared in a module that has the Option Private Module directive. Variables that should be accessible to other project should be declared in a different module that does not use the Option Private Module directive. In both cases, you need to declare using the Public keyword.

 

Option Compare Statement
Declares the default comparison method to use when comparing string data. Option Compare statement specifies the string comparison method (Binary or Text) for a class, module or structure. If an Option Compare statement is not included, the default text comparison method is Binary.

' Set the string comparison method to Binary (ie. case-sensitive). For example, "ABC” is less than "abc"
Option Compare Binary

' Set the string comparison method to Text (ie. case-insensitive). For example,  "ABC" is equal to "abc"
Option Compare Text

When you have the Option Compare Binary statement (case-sensitive) at the top of your module, there may be some times you want to override this and do a text case-insensitive Text comparison. Below is a simple re-usable function allowing you to do this so that you don't have to hard-code it every time. StrComp is given a return value of ‘0’ and performs a textual comparison so that String1 is now equal to String2.

Option Explicit
Option Compare Binary

Public Function BinaryToTextOptionCompare (String1 As String, String2 As String) As Boolean
      BinaryToTextOptionCompare = (StrComp(String1, String2, vbTextCompare) = 0)
End Function

The StrComp function has the following return values:

Condition if  StrComp returns:
string1 is less than string2 -1
string1 is equal to string2 0
string1 is greater than string2 1
string1 or string2 is Null Null



Option Base Statement
The syntax Option Base {0|1} specifies the first index number of an array. Because the default base is 0, the Option Base statement is never required. Option Base can appear only once in a module and must precede array declarations that include dimensions.

This example uses the Option Base statement to override the default base array subscript value of 0. The LBound function returns the smallest available subscript for the indicated dimension of an array. The Option Base statement is used at the module level only.
Option Explicit
Option Base 1                        
‘ set default array subscripts to 1

Public Sub OptionBaseExample()
Dim Lower As Long
Dim FirstArray(10), SecondArray(2, 4)
' declare array variables
Dim ThirdArray(0 To 10)               ' override default base subscript

' You can use LBound function to test lower bounds of the 3 arrays
Lower = LBound(FirstArray)       ‘ returns 1
Lower = LBound(SecondArray, 2)      ‘ returns 1
Lower = LBound(ThirdArray)              ‘ returns 0
End Sub

Return To Top

Sub Statement
Declares the name, arguments, and code of a Sub procedure. The general syntax of a subroutine is:

[{Public|Private|Protected|Friend|Protected Friend}] [Static] Sub name [(arglist)]
   [statements]
   [Exit Sub]
   [statements]
End Sub

Public
Optional. Procedures declared with the Public keyword have public access. This means that variables declared as Public are accessible to all other procedures in all modules in a directly referencing project unless Option Private Module is in effect.

Private
Optional. Procedures declared with the Private keyword have private access. . This means that variables declared as Private are accessible only to other procedures in the module where it is declared.

Protected
Optional. Procedures declared with the Protected keyword indicates they are accessible only from within their own class or from a derived class. Protected access can be specified only on members of classes. It is not a superset of friend access.

Friend
Optional and used only in a class module. Procedure declared with the Friend keyword indicates that the Sub procedure is visible throughout the project, but not visible to a controller of an instance of an object. This means they are only accessible from within their declaration context and from anywhere else in the same program.

Protected Friend
Optional. Procedures declared with the Protected Friend keywords have the union of protected and friend access. They can be used by code in the same program, as well as by code in derived classes. Protected friend access can be
specified only on members of classes.

Static
Used at procedure level to declare variables and allocate storage space. Static keyword indicates that the procedure's local variables are preserved between calls to the Sub. This means variables declared with the Static statement retain their values as long as the code is running until the module is reset or restarted.

name
Required. Name of the Sub procedure, and must follow standard variable naming conventions.

arglist
Optional. List of variables or expressions representing arguments that are passed to the Sub procedure when it is called. Multiple arguments are separated by commas. If you supply an argument list, you must enclose it in parentheses.

The example procedure below defines the sub name as ‘ChangeFont’ and takes three arguments: Addr As String, mActual As Single, mTarget As Single. Note that the calling sub calls this procedure by supplying its arguments in the correct position, each delimited by a comma - ChangeFont(Addr, mActual, mTarget). These 3 arguments passed to the called sub are: address of the cells, monthly value in the cell, and monthly target for the cell. The calling sub passes to ChangeFont sub a target value of 13000000, and if a cell value is greater than this target value, it formats the cell appropriately. The calling sub loops through all of the cells in the named Range called ‘MyRange’ with two nested For..Next Loops.

Option Explicit

Private Static Sub ChangeFont(Addr As String, mActual As Single, mTarget As Single)
    With ActiveSheet.Range(Addr)
        If mActual > mTarget Then        
' if argument is > mTarget value of $13000000
            .Font.ColorIndex = 3          ‘ format cells with Red font
            .Interior.ColorIndex = 6      ‘ fill cells with Yellow
            .Font.Bold = True             ‘ bold cells
        Else                              ‘ do nothing
        End If
    End With
End Sub


Sub FormatValue()
Dim NColumns As Integer, NRows As Integer, i As Integer, j As Integer, _
mTarget As Single, Addr As String, mActual As Single    
' declare local variables
NColumns = Range("MyRange").Columns.Count           ‘count number of columns
NRows = Range("MyRange").Rows.Count                 ‘ count number of rows
mTarget = 13000000
  For j = 1 To NColumns
    For i = 1 To NRows
        Addr = Range("MyRange").Cells(i, j).Address
‘ address of the cell
        mActual = Range("MyRange").Cells(i, j)      ‘ values of the cells in named Range
        Call ChangeFont(Addr, mActual, mTarget)     ‘ pass arguments to ChangeFont sub
    Next
  Next
End Sub

 

Optional list of arguments
The optional list of arguments (arglist) defines the arguments that will be passed to the procedure. The arguments have the following syntax:

[Optional] [ByVal|ByRef] [ParamArray] varname[()] [As type] [=defaultvalue]

Optional arguments are preceded by the Optional keyword in the procedure definition. You can also specify a default value for the optional argument in the procedure definition. For example:

Private Sub MyOptionalArgs(ByRef EmpID As Long, Optional mNote As String, _
  Optional mCity As String = "Singapore") As String
. . .
End Sub

The Optional keyword is optional, and can be used to specify that the argument is not required. If used, every argument following the first Optional argument must also be an optional argument. All arguments can be Optional, but they can not be entered in mixed order. By using Optional keyword as in the above example, you tell the procedure that you don’t have to insert the MyNote variable for the called sub to actually perform an operation. You can leave it to the user to provide specific additional elements such as input box, for your statement to execute. Optional can't be used for any argument if ParamArray is used. ByVal and ByRef determine whether the argument should be passed by value or by reference (the default), and the ParamArray keyword is optional, used only as the last argument in arglist to indicate that the final argument is an optional array of elements of the specified type. The ParamArray keyword allows you to pass an arbitrary number of arguments to the procedure. A ParamArray argument is always passed using ByVal. The variable
name varname is required, which represents the argument being passed to the procedure. Parenthesis () is required for array variables, which indicates that varname is an array. Type, which is Data type of the argument, is optional - Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, String (variable length only), Object, a user-defined type, or an object type. The above procedure will return a value MyOptionalArgs As String as long you enter an accepted value for the EmpID argument.

As you have seen, a benefit of using the Optional keyword is the use of default values. Providing specific default values for optional arguments in the definition part of some statements can save us on defining constants. Declaring constants in VB is not much different from variables, except that constants are declared in the Declaration section of a form code or module prior to any statements, whereas variables are declared inside Statements. Constants can not change values in the application. You can define the constants as shown below alternatively as the default values to be used in a sub procedure.

Const mNote As String  = "ptan91128"
Const mCity As String = "Singapore"

Sub MyOptionalArgs(ByRef EmpID As Long, Optional mNote As String = “ptan91128” _

  Optional mCity As String = "Singapore") As String

The ParamArray keyword is used in these contexts: Declare Statement, Function Statement, and Sub statement. Unlike VB6, in VB.NET the ParamArray keyword defines a true array object, which you can process using any of the methods of the array class, and ParamArray keyword also let you define arrays of any type, not just objects. Each argument to a ParamArray parameter can be of a different data type. That means the ParamArray parameter itself must be declared as an array of type Variant. Each argument supplied in the call to the function becomes a corresponding element of the Variant array. Snippet code below adopted from ADezii, shows that several calls are made to the AverageNum() function, each with a varying number of arguments, including invalid arguments. You can see the output through the Immediate Window.

Public Function AverageNum(ParamArray varNumbers() As Variant)
Dim varX, varY, intAverageNum As Integer
intAverageNum = 0
  For Each varX In varNumbers
    If IsNumeric(varX) And Not IsNull(varNumbers) Then
       varY = varY + varX
       intAverageNum = intAverageNum + 1
       AverageNum = varY / intAverageNum
       Else
    End If
  Next
End Function


‘ you can see result from these sample calls in the Immediate Window:

Debug.Print AverageNum(10, 30, 20)                 ' returns average number 20
Debug.Print AverageNum(23.15, 45.105, 456.56)      ' returns 174.938333333333
Debug.Print AverageNum(Null, "AB", "A12", 20, 30)  ' returns 25

Return To Top


More notes on Dim, ReDim and Static

Dim statement creates a space in memory for a variable. Variables declared with Dim at the procedure level are available only within the procedure. That means the variables remain in existence only as long as the procedure is executing. When it stops running, the values are not preserved and the memory is released. You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to re-declare a dimension for an array variable whose size was explicitly specified in a Dim statement, an error occurs. ReDim statement resizes the array and erases the elements. ReDim Preserve statement resizes the array but does not erase elements.

In the statement examples below, the line 1 Dim statement declares two variables as integer type. The Static statement and the Static keyword are similar, but they are used for different effects. The line 2 declares a procedure using the Static keyword as in Static Sub ChangeFont (), and then storage space for all local variables within that procedure is allocated once, and the value of the variables is preserved for as long as the program is running. For non-static procedures, storage space for variables is allocated each time the procedure is called and released when the procedure stops running. The Static statement is used to declare specific variables within non-static procedures to preserve their value for as long as the program is running. When you use Static statements within a procedure, put them at the beginning of the procedure with other declarative statements such as Dim. In line 3 the Static statement declares a variable X for a new instance of a worksheet. If the New keyword isn't used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object. When you use the New keyword in the declaration, an instance of the object is created on the first reference to the object. Line 4 statement declares a Variant array. Line 5 declares the named array ‘MyVar’ and assigns to it an integer data type. Line 6
Dim MyVar(5) creates an array with 6 elements (0-5), so there are altogether six A variables. Line 7 declares an array with 6 elements and assigns the Date data type. Line 9 statement declares a 2-dimensional, 5-by-10 array and assign to it Single data type. You can declare arrays with up to 60 dimensions. Line 10 ReDim MyVar(10) makes it an 11-element array but loses all the data in it. ReDim Preserve MyVar(15) in line 11 creates a 16-element array but keeps all existing data. In array, all subscripts start at 0 by default, unless you specify as Option Base 1 at the beginning of the module before you declare the array. See statement examples below.

Dim NColumns As Integer, NRows As Integer     ' declare two variables as integer
Static Sub ChangeFont(Addr As String, mActual As Single, mTarget As Single)
Static X As New Worksheet             ‘ declare a variable for a new instance of a worksheet
Dim MyVar()                            ' declare a dynamic Variant array
Dim MyVar() As Integer            ' declare MyVar array and assign Integer data type
Dim MyVar(5)                          ' declare an array with 6 elements
Dim MyVar(5) As Date                  ' declare an array with 6 elements and assign Date data type
    MyVar(3)= Format("12-24-2005", _     ' declare a 3-element array and assign a date to the 3 elements
  "General Date")
Dim MyVar(1 To 5, 1 To 10) As Single  ' declare a 5-by-10 multidimensional array and assign data type
ReDim MyVar(10)                       ‘ declare an 11-element array but loses all the data in it
ReDim Preserve MyVar(15)          ‘ declare an 16-element array but keeps all the data in it

Static is used at procedure level to declare variables and allocate storage space. You should only declare with a Static statement within a procedure when you want to retain the value of the variables between procedure calls until the module is reset or restarted. In class modules, variables declared with the Static statement retain their value in each class instance until that instance is destroyed. In form modules, static variables retain their value until the form is closed.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Variant variables are initialized to Empty. Each element of a user-defined type variable is initialized as if it were a separate variable.


Arrays
You can resize an array with Redim without losing the data. For details, see the Preserve keyword in the Help file on Redim. If you use the LBound/UBound in your code instead of hard-coding the dimension of the array, you can later change the size of the array without touching your code.

  • Option Base - Determines whether the lowest range of an array is 0 or 1
    • option base 1
  • Erase - Erases all values of an array
    • erase (arrayname)
  • Dim - Creates an array
    • dim arrayname(25)
  • Redim - Resets the bounds of an array (has option to save values)
    • redim arrayname(28)
  • UBound - Returns the upper dimension of an array
    • i = ubound (arrayname)
  • LBound - Returns the lower dimension of an array
    • i = lbound (arrayname)
  • Filter - Returns a subset of an array based on a filter
    • Filter (inputarray, searchstring)
  • Array - Yes, there is a function called array. It returns an array that has been filled with data from a list. It allows you to put the actual data values in the code to avoid having the user input it or to avoid having to read it from a file
    • ArrayName = Array (10, 20, 30)
  • Join - Concatenates strings within an array


Function Statement
Declares the name, arguments, and code that define a Function procedure. The syntax is:

[Public | Private | Friend] [Static] Function name [(arglist)] [As type]
[statements]
[Exit Function]
[statements]
End Function

arglist is optional. It is a list of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas. Each argument in the arglist part has the following syntax and parts (you can refer to the Sub statement that was described in earlier pages, for explanation on the component elements of the Function statement syntax and arglist argument syntax):

 [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

In some situations, you may not know ahead of time exactly how many arguments will be passed to a procedure (sub or function). If this is the case, then you would want to use the ParamArray keyword to define a procedure. ParamArray keyword enables the function to accept a variable number of arguments. Note that only one argument in a procedure declaration can be marked with ParamArray, and it must be the last or the only argument in the list. In the following first example adopted from http://paradoxes.info, the function combines text with a delimiter, and using a ParamArray there is no limit to the amount of text you can combine at once. This example combines street, suburb and city with a comma in between them, and if the suburb is empty, then it will return Street, City.

Option Explicit
Function CombineText(myDelimeter As String, ParamArray myText()) As String
   Dim v As Variant
   Dim s As String
   For Each v In myText
      If Len(s) = 0 Then
         s = v
      ElseIf Len(v) > 0 Then
         s = s & myDelimeter & v
      End If
   Next
   CombineText = s
End Function

' You can invoke the above function as:
Dim Address As String
Dim MyVar(4) As String
MyVar(0) = "AMSEA"
MyVar(1) = "3 Business Park Vista"
MyVar(2) = "S486051"
MyVar(3) = "Singapore"
Address = CombineText(", ", MyVar(0), MyVar(1) & vbcrlf & MyVar(2), MyVar(3))
debug.print Address

' Using the ParamArray array parameter, this second example returns the sum of any number of values passed to it:
Function Sum(ParamArray myArgs() As Variant) As Single
Dim total As Single
Dim i As Integer
For i = 0 To UBound(myArgs)
    total = total + myArgs(i)
Next i
Sum = total
End Function

Dim MyVar(4) As Single, x As Single
MyVar(0) = "5.5"
MyVar(1) = "4.5"
MyVar(2) = "5"
MyVar(3) = "15"
x = Sum(MyVar(0), MyVar(1), MyVar(2), MyVar(3))

Like a Sub procedure, Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. For Function procedures, the data type of the procedure determines the data type it returns. You can use an As clause following arglist to specify the return type of the function. Within arglist, you can use an As clause to specify the data type of any of the arguments passed to the procedure. If you don’t explicitly specify using Public, Private, or Friend, Function procedures are Public by default. If Static isn't used, the value of local variables is not preserved between calls. The Friend keyword can only be used in class modules. However, Friend procedures can be accessed by procedures in any module of a project. You can define a Function procedure inside a module, class, interface, or structure, but you can't define a Function procedure inside another Function, or Sub procedure because all executable code must be in procedures.

You call a Function procedure using the function name, followed by the argument list in parentheses. You can omit the parentheses only if you are not supplying any arguments. A function can also be called using the Call statement, in which case the return value is ignored. To return a value from a function, assign the value to the function name or include it in a Return statement.. When the Function procedure returns to the calling program or your main procedure, execution continues with the statement following the statement that called it. Any number of value assignment statements and Exit Function statements can appear anywhere within the procedure. The Exit Function statement will cause an immediate exit from a Function procedure. If you use Exit Function without assigning a value to the variable name, the variables will initialize, and the function returns the default value appropriate to the argument type: a numeric function returns 0 (for data type Byte, Char, Decimal, Double, Integer, Long, Short, and Single), a string function returns a zero-length string (""), a Boolean function returns False, a Date function returns #1/1/0001 12:00 AM#, and a Variant function returns Empty. A function that returns an object or array reference returns Nothing if no object or array reference is assigned to the variable name (using Set statement) within the Function.

The following procedure example assigns the return value to the function name myFirstSheet and then uses the Exit Function statement to return.

Function myFirstSheet(i As String) As String
  ‘do something…
  myFirstSheet = "template"
  ‘do something…
  Exit Function
End Function

Some caution on Function statement:
1) Function
procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword usually isn't used with recursive Function procedures.

2) A Function procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined
at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that your procedure refers to that module-level name. Explicitly declare variables to avoid this kind of conflict. Always use Option Explicit statement to force explicit declaration of variables.
 

Set statement
Set statement assigns an object reference to a Variable or Property. The Dim, Private, Public, ReDim, and Static statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object.

’ Set statement assigns object references to variables
Dim objX, objY, MyStr

Set objY = objX                        ' assign object reference

' objX and objY now refer to the same object
objX.Text = "wiliam"                   ' initialize property
MyStr = objY.Text                      ' returns ‘william’

' discontinues association, and now objX no longer refers to objY
Set objX = Nothing                     ' release the object

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because such variables are references to the object rather than copies of the object, any change in the object is reflected in all variables that refer to it. However, when you use the New keyword in the Set statement, you are actually creating an instance of the object on the first reference to the object. If the New keyword isn't used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object.

Note: If you are using VB.NET and the external procedure was created on VB 6, you must make sure that the data types are matching. For example, if you declare a reference to a VB 6 procedure with an Integer argument (two bytes in VB 6), you must identify that argument as Short in the Declare statement, because that is the two-byte integer type in Visual Basic .NET.



Return Statement
It branches to and returns from a subroutine within a procedure. You can use GoSub and Return statement anywhere in a procedure. A subroutine can contain more than one Return statement, but the first Return statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed GoSub statement. Note that you can't enter or exit Sub procedures with the GoSub...Return statement.

The following example uses GoSub to call a subroutine within a Sub procedure. The Return statement causes the execution to resume at the statement immediately following the GoSub statement. The Exit Sub statement is used to prevent control from accidentally flowing into the subroutine.

Sub GoSubReturnTest()
Dim i As Long, Total As Currency, itemCost As Currency
itemCost = 3500
i = InputBox("Enter your discount $amount")    
' solicit a value from user

    If i > 0 Then GoSub MyRoutine               ' use routine if user enters a positive number
    Exit Sub    ' Use Exit to prevent an error
MyRoutine:
    Total = i + itemCost     
' execute multiplication
    Debug.Print "Total is " & Format(Total, "currency")
    Return                   
' returns control to statement
End Sub
 

Deftype Statement
Deftype statements in VB 6 are not supported in VB. Example below shows various uses of the Deftype statements to set default data types of variables and function procedures whose names start with specified characters. The default data type can be overridden only by explicit assignment using the Dim statement. Deftype statements can only be used at the module level.

DefInt A-K                 ' variable names beginning with A through K default to Integer
DefStr L-Z                 ' variable names beginning with L through Z default to String
iNum = 2                   ' initialize Integer
strVar = "Nice day"        ' initialize String
anyVar = " Nice day "      ' causes "Type mismatch" error
Dim iNum As Double         ' Dim statement explicitly set the data type to Double
iNum = 2.345678            ' assign a Double data type

The Def statement names below determine the different data types..

Statement Data Type
DefBool Boolean
DefByte Byte
DefInt Integer
DefLng Long
DefCur Currency
DefSng Single
DefDbl Double
DefDec Decimal
DefDate Date
DefStr String
DefObj Object
DefVar Variant

Return To Top


Declare Statement
Visual Basic provides a lot of functionality in its native functions and methods. However, sometimes you need some feature that simply isn't available using the native VB methods. This is where the Win32 API (Application Programming Interface) comes in. Windows provides several thousand functions that are available to a VB programmer (or any other language that supports them such as C\C++). To use an API in your code procedure all you need to do is include the appropriate Declare statement.

Declare statement is used at module level to declare references to external procedures in a dynamic-link library (DLL). A DLL file is nothing more than a collection of functions and subroutines that can be loaded dynamically, when your Visual Basic program requests one of its components at run time. Because DLL procedures reside in files that are external to your Visual Basic application, you must specify where the procedures are located and identify the arguments with which they should be called. DLL procedures declared in standard modules are public by default and can be called from anywhere in your application. You can place the Declare statements in class modules if the Declare statements are Private. Procedure names are case-sensitive in 32-bit versions of Visual Basic.

To declare a DLL procedure, you add a Declare statement to the declarations section of the code window. If the procedure does not returns a value, write Declare as a Sub:
[
Public | Private] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])]

If the procedure returns a value, write the declare as a function:
[Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

Below are explanations for some of the different elements of the Declare statement syntax:

name
Required. Any valid procedure name. Note that DLL entry points are case sensitive.

Lib    
Required. Indicates that a DLL or code resource contains the procedure being declared.
The Lib clause is required for all declarations.

Libname
Required. Name of the DLL or code resource that contains the declared procedure.

Alias
Optional. Indicates that the procedure being called has another name in the DLL. This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a public variable, constant, or any other procedure in the same scope. Alias is also useful if any characters in the DLL procedure name aren't allowed by the DLL naming convention.

aliasname   
Optional. Name of the procedure in the DLL or code resource. If the first character is not a number sign (#), aliasname is the name of the procedure's entry point in the DLL. If (#) is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point.

The arglist argument has the following syntax and parts:
[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type]

Empty parentheses indicate that the Sub or Function procedure has no arguments and that Visual Basic ensure that none are passed. In example below, First takes no arguments. If you use arguments in a call to First, an error occurs:
Declare Sub First Lib "MyLib"()

If you include an argument list, the number and type of arguments are checked each time the procedure is called. In the following example, First takes one Long argument:
Declare Sub First Lib "MyLib" (X As Long)

Note: You can't have fixed-length strings in the argument list of a Declare statement; only variable-length strings can be passed to procedures. Fixed-length strings can appear as procedure arguments, but they are converted to variable-length strings before being passed. The vbNullString constant is used when calling external procedures, where the external procedure requires a string whose value is zero. This is not the same thing as a zero-length string ("").

To find the appropriate Declare statement you need to use you can use a tool called the Win32 API Viewer that comes with VB6. Open your API Text Viewer, go to the File Menu/Load Text File and open the file called WIN32API.TXT (it is resided in C:\Program Files\Microsoft Visual Studio\Common\Tool\Winapi). Once you have loaded the text file the Available Items list will populate with all the available API's. You can type in the name of API or use the scrollbar to look for the API, and double-click it (but ensure the Public option is selected). Click Copy to copy it to the clipboard and go to your VB to add this in your module. Once you have done this, you can use that function in your VB project as if it was a native VB function. Your help files or MSDN have the documentation that explain for each particular API you wish to use. Below is a simple example of using the GetTickCount() API to benchmark some code. GetTickCount() returns the number of milliseconds that have elapsed since the system was started, up to 49.7 days.
This can also be used for timing how long it takes for a certain chunk of code to execute (by calling it before and after and calculating the difference). GetTickCount() API uses Kernel32.lib Kernel32.dll file.

Public Declare Function GetTickCount Lib "kernel32" Alias "GetTickCount" () As Long

Public Sub BenchmarkSomeCode()
Dim lngStart As Long
Dim i As Long
Dim lngSum As Long
lngStart = GetTickCount()

' benchmarking this code
For i = 1 to 100000000
lngSum = lngSum + 1
Next i
MsgBox CStr(GetTickCount() - lngStart)
End Sub

 

Return To Top

 

Summary note on Declaration statements

Declaration statements in general are pretty simple, but getting to the details and get it right can sometimes be tricky even for experienced programmers. Focus on understanding Dim/ReDim/Public/Private/Sub/Function/Type and Set, and commit these to your memory as you will use it in almost every procedure. The summary list below will give a memory refresher. You have to refer to MSDN library and books for examples to get better understanding.

  • Dim - Used to define a variable as a certain type
    • Dim i as integer, r as single
    • You can use the Option Explicit to make sure that VB forces you to declare every variable you use. DIM is that simplest way to declare a variable
  • ReDim - Used to change the dimensions of a dynamic array
    • Redim arrayname(37)
    • Don't be afraid of this one. You can use ReDim to create an array whose size grows by 1 every time you want to add a number to it. Then, the UBound tells you how many numbers you've added.
  • Static - Establishes a procedure variable which keeps its value between calls
    • Static i as integer
    • For example, if you want to keep track of how many times you've been in a procedure, set a counter as STATIC and increment it by one for each visit to the procedure. It will never go away until the program is terminated.
  • Public - Creates a variable which can be accessed outside its own procedure
    • Public i as integer
    • Even if you're the only programmer writing code in your application, use of Private vs Public will help catch errors if you inadvertently try to access an out-of-scope variable
  • Private - Creates a variable that is read only in its own procedure or module, according to where the declaration took place.
    • Private i as integer
    • Use this as often as possible to avoid unnecessary exposure of your variables to coding mistakes.
  • Sub - Defines a procedure which can execute a block of code
    • Sub NewProcedure (var1 as integer, var2 as string)
    • Be sure to check out HELP for how to handle Sub arguments. There are more questions and mistakes made concerning the use of arguments than just about anything else I've seen.
  • Function - Declares a procedure which can return a value
    • Function NewFunction (var1 as integer, var2 as string) as SINGLE
    • This is actually the most versatile of the Sub/Function procedure types. It can do anything a Sub can do as well as returning a value for use in an expression.
  • Call - Transfers control to a Sub or Function (is optional)
    • Call Procedure 1
    • Since the use of CALL is optional, forget you ever saw it
  • CallByName - Executes a method of an object or set/returns a property
    • CallByName(form1,procedurename,vbMethod)
    • The really cool thing about this is that you don't have to hardcode a procedure call. Just use a string variable with the name of the procedure to call.
  • Option Explicit - Instructs VB to force an explicit declaration of all variables
    • Option Explicit
    • You're borderline stupid if you don't use it to catch typing errors. Set up the VB IDE to automatically include this in all projects.
  • Option Compare - Instructs VB on how to make string comparisons
    • Option Compare Binary
    • This can add case-insensitivity for those times when you don't want to hard-code it
  • Option Private - Prevents a module's content from being referenced outside a project.
    • Option Private Module
    • Generally doesn't apply to most VB applications. If you find a good use for it let me know.
  • Property Get - Declares how to get the value of a property
    • Property Get Name()
    • You won't use this much until you get into creating classes of your own
  • Property Let - Declares how to assign a value to a property
    • Property Let Name()
    • You won't use this much until you get into creating classes of your own
  • Property Set - Declares how to set a variable reference to an object
    • You won't use this much until you get into creating classes of your own
  • Set - Assigns an object reference to a variable
    • Set X = form1.txtInputFromUser
    • Very useful for making code more readable or simply to cut down on how much typing you have to do!
  • Let - Precedes assignment of a value to a variable
    • Let i = 3
    • It's optional, no one uses, so forget you ever saw it
  • Type...End Type - Creates a user defined part type which consists of standard VB data types
    • type anytypename
    • one as string
    • two as integer
    • three as boolean
    • End Type
    • This is a really excellent way to keep several kinds of data under one variable name. Plus, you can PUT or GET a user-defined type with a single line of code.
  • Const - Creates a variable whose value is fixed
    • const anyname
    • Basically, use this to give easy to remember names to values. For example, suppose you use the value 37.2 a lot in your code, then if you put CONST MyAge = 37.2 in your code you'll be able to insert the MyAge where the 37.2 should have gone. Easier to type and easier to read. Also, you can chane the value of the constant by changing only the declaration line of code, rather than searching out every place the value was used!
  • Declare - Used to define a procedure that exists in another file
    • declare functionname (arg1 as integer, arg2 as string) as integer
    • ArrayName = Array (10, 20, 30)
    • Implements - Specifies a class to be implemented in a module
    • Friend - Allows procedure to be callable from modules outside the class
    • GetObject - Return a reference to an ActiveX component
    • CreateObject - Creates and returns a reference to an ActiveX object
    • GetAutoServerSettings - Returns information about the state of an ActiveX component's registration.
    • Enum - Declares a type for an enumeration
    • Event - Declares a user-defined event
    • TypeName - Returns the type of data in a variable
    • VarType - Returns the type of data in a variable
    • DefType - Sets the default data type of variables DefInt A-Z
    • IS - A variety of data type or status checking options IsArray, IsBindable, IsBroken, IsDate, IsDirty, IsEmpty, IsError, IsMissing, IsNull, IsNumber, IsObject, IsReady, IsRootFolder

Return To Top

 

Assignment Statements

Assignment statement sets a variable or property of an object to a specific value. In a layman term, Assignment statement takes the value on the right side of the assignment operator (=) and storing it in the element on the left. For example, x=123, it means the assignment statement stores the literal value 123 in the variable x. See more examples below.

‘ it sets the value of the MyNextNumber variable to the sum of the MyNumber variable plus 12.
MyNextNumber = MyNumber + 12

‘ you use the Set statement when you’re assigning values to object variables

Dim myRng As Range
Set
myRng = Worksheets("Main").Range("A1:K1")
With myRng.Font
   .Bold = True
   .ColorIndex = 3
End With

’ you use Let statements to assign one record variable to another only when both variables are of the same user-defined type. Let statement is optional, and nobody uses it any longer, so you can omit it.
Dim yourPWD As String
Let yourPWD = InputBox(key in your password:"



The following are the Assignment Operators defined in Visual Basic.

  = Operator
  ’ assigns a value to a variable or property on the left.
Dim testInt As Integer
Dim testString As String
Dim testButton As System.Windows.Forms.Button
Dim testObject As Object
testInt = 42
testString = "This is an example of a string literal."
testButton = New System.Windows.Forms.Button()
testObject = testInt
testObject = testString
testObject = testButton
 
  ^= Operator
  ’ raises the value of a variable or property to the power of an expression and assigns the result back to the variable or property
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 ^= var2 ' the value of var1 is now 1000
 
 
*= Operator
  ’ Multiplies the value of a variable or property by the value of an expression and assigns the result to the variable or property
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 *= var2 
‘ the value of var1 is now 30
 
  /= Operator
  ’ Divides the value of a variable or property by the value of an expression and assigns the floating-point result to the variable or property
Dim var1 As Integer = 12
Dim var2 As Integer = 3
var1 /= var2 
‘ the value of var1 is now 4
 
 
\= Operator
  ’ Divides the value of a variable or property by the value of an expression and assigns the integer result to the variable or property
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 \= var2 
‘ the value of var1 is now 3
 
  += Operator
  ' Adds the value of a numeric expression to the value of a numeric variable or property and assigns the result to the variable or property. Can also be used to concatenate a String expression to a String variable or property and assign the result to the variable or property.
' This part uses numeric variables.
Dim num1 As Integer = 10
Dim num2 As Integer = 3
num1 += num2 
‘ the value of num1 is now 13

' This part uses string variables
Dim str1 As String = "10"
Dim str2 As String = "3"
str1 += str2 
‘ the value of str1 is now "103"

 
 
-= Operator
  ’ Subtracts the value of an expression from the value of a variable or property and assigns the result to the variable or property
Dim var1 As Integer = 10
Dim var2 As Integer = 3
var1 -= var2 
' the value of var1 is now 7
 
  &= Operator
  ‘Concatenates a String expression to a String variable or property and assigns the result to the variable or property
Dim var1 As String = "Hello "
Dim var2 As String = "World!"
var1 &= var2 
' the value of var1 is "Hello World!"
 
 
 
The following contains a list of the Relational Comparison operators and the example 
conditions that determine whether result is True or False.
 
Operator                                     True if         False if
< (Less than)                               2 < 3          2 >= 4
<= (Less than or equal to)            2 <= 2        2 > 3
> (Greater than)                          2 > 1          2 <= 1
>= (Greater than or equal to)        2 >= 1        2 < 1
= (Equal to)                                 2 = 2          2 <> 2
<> (Not equal to)                         2 <> 3        2 = 3
Note: The = Operator is also used as an assignment operator
 
 
  AND Operator
  Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck As Boolean
firstCheck = a > b And b > c
     ‘returns True
secondCheck = b > a And b > c  ‘returns False
 
 
NOT Operator
  Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck As Boolean
firstCheck = Not (a > b)     
‘ returns False
secondCheck = Not (b > a)     ‘ returns True
 
  OR Operator
  Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b Or b > c  
‘ returns True
secondCheck = b > a Or b > c  ‘ returns True
thirdCheck = b > a Or c > b   ‘ returns False
 
 
XOR Operator
  Dim a As Integer = 10
Dim b As Integer = 8
Dim c As Integer = 6
Dim firstCheck, secondCheck, thirdCheck As Boolean
firstCheck = a > b Xor b > c   
‘ returns False
secondCheck = b > a Xor b > c     ‘ returns True
thirdCheck = b > a Xor c > b       ‘ returns False
 

Return To Top


Executable Statements

Executable statements can call or execute a procedure, method, function, loop, and they can branch to another place in the code, loop through blocks of code, or evaluate an expression. Executable statements include Assignment Statements, which assign a value or expression to a variable or constant. Executable statements mostly contain mathematical or conditional operators.

We use executable statements to do the following:
   Call another procedure in your own code, example:

   Call Macro1
   Activate a method belonging to an object, example:
   ActiveWorkbook.Worksheets.Add
   Control the order in which other statements are executed, example:

   If ActiveSheet.AutoFilterMode = False Then
   Execute one of the built-in VBA statement or functions. example:
   ChDir "C:\william91128\GPP_DSM\"


Two executable statements below: the If…Then statement tests to see if there is a sheet named ‘main’ in the active workbook. If the sheet name is not ‘main’, the Delete method would delete the sheet. If Sheet1 ‘name is not ‘main’, it would rename Sheet1 to ‘main’. The For Each…Next statement iterates through every sheet.

Dim ws As Object
  For Each ws In Sheets
    If ws.Name <> "main" Then ws.Delete
        If Sheets(1).Name <> "main" Then
        Sheets(1).Name = "main"
    End If
  Next ws


The following example uses a For Each...Next statement to iterate through each cell in a range named MyRange on a Sheet named ‘main’ of an active Excel workbook. The If...Then...Else statement in the example checks the value of the cell. If the value is greater than $350, the With statement sets the Bold and ColorIndex properties of the Font object for that cell. The Next statement calls the next cell c in the collection of cells contained in MyRange.

Dim c As Range
Const x As Currency = "$350"
For Each c In Worksheets("main").Range("MyRange").Cells
    If c.Value > x Then
        With c.Font
            .Bold = True
            .ColorIndex = 3
        End With
    End If
Next c


In the following example, Each Case statement in the Select Case structure is compared against the test expression. If a match is found, the statements accompanying the Case are executed and update Column C. Only the statement block of the first matching Case expression is executed. In the end, Case Else expression executes if none of the Case expressions evaluates to True.

Dim lastrow As Long, i As Long
Range("B1") = "Unit Cost"
Range("C1") = "Material Class"           
lastrow = Range("A65536").End(xlUp).Row
For i = 2 To lastrow
    Select Case Worksheets("Sheet1").Cells(i, 2).Value
    Case Is > 10000
    Cells(i, 3) = "A"

    Case Is > 5000
    Cells(i, 3) = "B"

    Case Is > 2000
    Cells(i, 3) = "C"

    Case Is > 100
    Cells(i, 3) = "D"

    Case Else
    Cells(i, 3) = "E"
End Select
Next i


While...Wend statement in the following example loops until an event is false. Two input boxes ask for string and the Column letter you want to find, then insert a column to the right. Whenever a match in your search column is found , it fill the cell to the right with a value of 1
Dim col As String, I As Integer
Dim addr, sp, str
str = InputBox("Enter the string to find")
col = InputBox("Enter column letter to search")
Columns(col & ":" & col).Offset(, 1).EntireColumn.Insert
Columns(col & ":" & col).Select
On Error GoTo handler:

Selection.Find(What:=str, After:=ActiveCell, LookIn:=xlFormulas, _
MatchCase:=False).Activate
addr = ActiveCell.Address
sp = Split(ActiveCell.Value, str)
Range(addr).Offset(0, 1).Value = Range(addr).Offset(0, 1).Value + UBound(sp)

While I = 0
Selection.FindNext(After:=ActiveCell).Activate
If ActiveCell.Address = addr Then
  I = 1
Else
  sp = Split(ActiveCell.Value, str, -1)
  Range(ActiveCell.Address).Offset(0, 1).Value = Range(ActiveCell. _
  Address).Offset(0, 1).Value + UBound(sp)
End If
Wend

handler:
If Err.Description <> "" Then
MsgBox "no match is found"
End If


The Split function has this syntax:
Split(expression [, delimiter [, count [, compare]]])

  • "Expression" is a required string expression containing substrings and delimiters.
  • "Delimiter" is an optional string identifying the delimiter character. By default, a space character (" ") is considered to be the delimiter.
  • "Count" is an optional number of substrings to return. The default is -1, which indicates all substrings are to be returned.
  • "Compare" is an optional numeric value signifying how the comparison should take place for evaluating substrings. A 0 indicates binary comparison; a 1 (the default) signifies textual comparison.


You use With statements in the following example to reduce the number of object references:
With Selection
    .NumberFormat = "$#,##0.00"
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlBottom
    .WrapText = True
    .ShrinkToFit = False
    .MergeCells = False
    .Font.Name = "TimesNewRoman"
    .Font.Size = 10
    .Font.ColorIndex = 3
    .Interior.ColorIndex = 6
    .Interior.Pattern = xlSolid
End With


The following Loops and Conditional Decisions, Operators, Error-Handling, and the miscellaneous functions and command take out a lot of the need in your executable statement. My advice is take some time to understand and practice - become a master of each one !

Loops and Conditional Decisions
  '  If..Then..Else - Performs code based on the results of a test

        If A>5 Then Print "A is a bit number!"
  '
  For...Next - Loops a specified number of times
        For i = 1 to 5: print #1, i: next i
  '
  For Each ... Next - Walks through a collection
     
  For Each X in Form1.controls: Next X
  '
  While...Wend - Loops until an event is false
        while i < 5: i = i +1: wend
  '  Select Case - Takes an action based on a value of a parameter
        select case i
        case 1 : print "it was a 1"
        case 2 : print "it was a 2"
        end select
  '  Do...Loop - Loops until conditions are met
        do while i < 5 : i = i + 1 : loop
  '  IIF - Returns 1 of two parts, depending on the value of an expression
        result = IIF (testexpression, truepart, falsepart)
  '  Choose - Selects and returns a value from a list of arguments
        Choose (index, "answer1", "answer2", "answer3")
  '  With - Executes a series of statements on a single object
        With textbox1
        
.Height = 100
        
.Width = 500
        End With
  '  End - Immediately stops execution of a program
        End
  '  Stop - Pauses execution of a program (can restart without loss of data)
        Stop
  '  Switch - Returns a value associated with the first true expression in a list
        result = Switch (testvalue1, answer1, testvalue2, answer2)
  '  GoTo - Switches execution to a new line in the code
        GoTo Line1
  '  GoSub ... Return - Switches execution to a new block of code and then returns
        GoSub Line1
  '  On .. GoSub - Branch to a specific line of code then return at the next Return statement
        On Number GoSub Line1, Line2, Line3
  '  On .. GoTo - Branch to a specific line of code
        On Number GoTo Line1, Line2, Line3
 

Operators
Here are the VB operators used to perform mathematical operations on one or more variables. Aside from the normal
multiply/add/substract and divide, you will find the AND, OR, Not Equal, MOD and Integer Division operators very useful.

          / - Normal division
 
         \ - Integer division (truncates the answer)
 
         ^ - Exponentiation operator
 
         * - Multiply
 
         + - Plus
 
         - - Minus
 
         = - Equal
 
         > - Greater Than
 
         < - Less Than
 
         <> - Not Equal
 
         >= - Greater than or equal
 
         <= - Less than or equal
 
         AND - Defines a boolean value that is the AND of two values
        result = expression1 AND expression2
 
         OR - Defines a boolean value that is the OR of two values
        result = expression1 OR expression2
 
         XOR - Defines a boolean value that is the exclusive OR of two values
        result = expression1 XOR expression2
 
         NOT - Defines an opposite boolean value
        A = NOT B
 
         EQV - Performs a logical equivalence on two expressions (result is true if both expressions are true)
        result = expression1 EQV expression2
 
         IMP - Performs a logical implication on two expressions
        result = expression1 IMP expression2
 
         IS - Determines if 2 variables reference the same object
        result = object1 IS object2
 
         LIKE - Determines if one string matches a pattern
        result = string LIKE pattern
 
         MOD - Returns the integer remainder of a division
        i = 27 MOD 5

 

Error Handling
  '  On Error - Enables an error-handling routine
        On Error GoTo Line2 (if error occurs, go to line2)
        On Error Resume Next (if error occurs, continue executing next line of code)
        On Error Goto 0 (disables error handling)
  '  Resume - Used to resume execution after a error-handling routine is finished
        Resume
        Resume Next
        Resume Line1
  '  CVErr - Returns an error type variable containing a user-specific error number
        X = CVError(13)
  '  Error - Simulates the occurrence of an error
        Error 23


Miscellaneous
MsgBox, DoEvents, Shell, and Command
functions are indispensable in certain occasions, but the others are equally useful in some other different circumstances.
  '
  MsgBox - A built-in dialog box that gives a message and allows a user input
     ►   i = msgbox "Read this!", vbokonly, "Test Message"
  '  DoEvents - Allows VB to complete pending tasks
     ►  doevents
  '  Shell - Executes a 2nd program from within the current program
     ►  shell "notepad.exe"
     ►  Note - VB does not wait for the Shell'd program to quit before executing the next line of code!
  '  Command - Gives any text that followed a VB .EXE execution command
     ►  temp$ = command
  '  Environ - Returns the system environmental space content
     ►  temp$ = environ
  '  Beep - Makes the computer beep once.
     ►  beep
  '  InputBox - A built-in dialog box that allows entry of a text string
     ►  inputbox "Input a value!", 5
  '  AddressOf - Provides an entry point for an external program to use a procedure
     ►  AddressOf ( procedurename )
  '  AppActivate - Activates an applications window
     ►  AppActivate ( windowtitle )
  '  RaiseEvent - Fires an event declared at module level
     ►  RaiseEvent ProcedureName
  '  Load - Load an object
     ►  load form1
  '  Unload - Unload an object
     ►  Unload form1
  '  LoadPicture - Load a picture into a control property
     ►  form1.picture = loadpicture (filename)
  '  SavePicture - Save a picture to a file
     ►  SavePicture(form1.picture,filename)
  '  LoadResData - Load the data from a resource file
     ►  LoadResData(index,format)
  '  LoadResString - Load a string from a resource file
     ►  LoadResString(index,format)
  '  SendKeys - Send keys to another app as though they were from the keyboard
     ►  Sendkeys {DOWN}
  '  QBColor - Returns a value corresponding to the original QB values 0-15
     ►  form1.backcolor = QBcolor (12)
  '  RGB - Returns a color value by inputting the red, green, and blue parts
     ►  form1.backcolor = RGB (12,128,256)
  '  Me - Refers to the current object, usually the active form
     ►
  print Me.caption

Return To Top

This site was created in Feb.2007
by William Tan