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 Before you can
use a variable, you must first declare it. When you declare a variable,
you are: 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 Option
Explicit statement 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 Compare Statement
' Set the string
comparison method to Binary (ie. case-sensitive). For example, "ABC” is
less than "abc" '
Set the string comparison method to Text (ie. case-insensitive). For
example, "ABC" is equal to "abc"
Option Explicit
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
Sub Statement 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 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
Optional list of arguments 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, _ 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" 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)
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.
[Public | Private | Friend] [Static]
Function name [(arglist)] [As type] 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
' You can
invoke the above function as:
' Using the ParamArray array parameter, this second example returns the sum of any
number of values passed to it:
Dim MyVar(4) As Single, x As Single 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: Set statement Set objY = objX ' assign object reference ' objX
and objY now refer to the same object '
discontinues association, and now objX no longer refers to objY 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. 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() 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
|
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 |
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:
[
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
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
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.
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
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 |
-= 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 |
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:
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]]])
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
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
This site was created
in Feb.2007 by William Tan |