Aaron Wirth

Complete List Of Visual Basic Commands
Note: To go to pages use the Page function in the View – Go To menu, shortcut: Shift + Ctrl + N. Press Ctrl + Home to return to Table of Contents.

Table of Contents Strings (P3)
Left and Right functions (P3) LCase and UCase functions (P4) FormatDateTime (P6) Len Function (P7) InstrRev (P9) Replace Function (P10) Base 0 & 1 (P3) Formatting (P4) Mid function (P7) InStr (P8) Asc Function (P9) StrComp (P10) Trim, LTrim, and RTrim functions (P3) FormatCurrency, Percent & Number (P5) Chr Function (P7) String function (P9) Space Function (P9) StrConv function (P10)

Math (P12)
Val Function (P12) Rnd & Randomize (P12) Abs function (P13) Round (P12) Int and Fix functions (P12) Sgn (P13) Sin, Cos, Tan, Log, Atn & Exp Functions (P13) Other Math Functions (P14)

Logic (P15)
Mod Operator (P15) Xor Operator (P17) Is Operator (P18) And (P15) If Not (P17) Or Operator (P16) Like Operator (P17)

Arrays (P19)
Erase Statement (P19) Array Function (P20) Dim (P19) ReDim (P19)

Files/Folders (P21)
Dir (P21)

CurDir (22) Kill Function (P23) FileLen (P23) GetAttr (P24) Open Function (P26) Line Input (P27) Lof Function (P28)

ChDir (P22) ChDrive (P22) MkDir (P22) RmDir Function (P23) FileDateTime (P23) FileCopy (P24) Cut, Copy & Pasting Text (P24) SetAttr (P25) FreeFile function (P25) Close Statement (P27) EOF Function (P27) Print Function (P28)

Error Handling (P29)
On Error Statement (P29) Error Function (P30) Resume, Resume Next, Resume Line (P29)

Declarations (P31)
Function Procedures (P31) CallByName (P33) Option Private (P34) Type…End Type (P35) Let Statement (P36) DefType (P39) Const (P32) Call Statement (P33) Option Explicit (P34) Option Compare (P34) GetObject (P35) CreateObject (P36) TypeName (P37) VarType (P38)

Date/Time (P41)
Date (P41) Timer (P41) DateSerial (P44) Month (P45) Day (P46) TimeSerial (P47) Time (P41) Now (P41) DateAdd (P42) DateDiff (P42) DateValue (P44) Year (P45) MonthName (P45) WeekDayName (P45) Hour (P46) Minute (P47) TimeValue (P48) WeekDay (P48)

1

Aaron Wirth

Miscellaneous (P50)
MsgBox (P50) QBColor (P53) Load (P54) LoadPicture (P57) Shell (P51) RGB (P52) Beep (P53) InputBox (P53) UnLoad (P54) SendKeys (P55) AppActivate (P57)

Values (P58)
IsNull (P58) IsEmpty (P58) IsNumeric (P58)

Loops and Conditional (P59)
If...Then...Else (P59) End Statements (P59) Stop Statement (P60) Switch (P61) GoTo Statement (P61) On...GoSub, On...GoTo Statements (P62) GoSub...Return Statement (P62) With Statement (P63) For...Next Statement (P63) While...Wend Statement (P64) Do...Loop Statement (P65) IIf Statement (P65) For Each...Next Statement (P66) Select Case Statement (P67)

2

Aaron Wirth

Strings
Left and Right functions
Returns a Variant (String) containing a specified number of characters from the right side of a string.

Syntax
Left(string, length) Right(string, length) Example: Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Right(AnyString, 1) ' Returns "d". MyStr = Right(AnyString, 6) ' Returns " World". MyStr = Right(AnyString, 20) ' Returns "Hello World". Part string length Description Required. String expression from which the rightmost characters are returned. If string contains Null, Null is returned. Required; Variant (Long). Numeric expression indicating how many characters to return. If 0, a zero-length string ("") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Base 0 & 1
Option Base {0 | 1} Because the default base is 0, the Option Base statement is never required. If used, the statement must appear in a module before any procedures. Option Base can appear only once in a module and must precede array declarations that include dimensions. The Option Base statement only affects the lower bound of arrays in the module where the statement is located. Example: Dim iNumber(15 To 114) As Integer

Trim, LTrim, and RTrim functions
Returns a Variant (String) containing a copy of a specified string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim). The required string argumhent is any valid string expression. If string contains Null, Null is returned. Syntax LTrim(string) RTrim(string) Trim(string) Example: Dim MyString, TrimString MyString = " <-Trim-> " ' Initialize string. TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ". TrimString = RTrim(MyString) ' TrimString = " <-Trim->". TrimString = LTrim(RTrim(MyString)) ' TrimString = "<-Trim->". ' Using the Trim function alone achieves the same result. TrimString = Trim(MyString) ' TrimString = "<-Trim->".

3

A constant that specifies the first week of the year. firstweekofyear]]]) The Format function syntax has these parts: Part expression format firstdayofweek firstweekofyear Description Required. Null is returned. Settings The firstdayofweek argument has these settings: Constant vbUseSystem VbSunday vbMonday vbTuesday vbWednesday vbThursday vbFriday vbSaturday Value 0 1 2 3 4 5 6 7 Description Use NLS API setting. The required string argument is any valid string expression. format[. Sunday (default) Monday Tuesday Wednesday Thursday Friday Saturday The firstweekofyear argument has these settings: Constant vbUseSystem vbFirstJan1 vbFirstFourDays Value 0 1 2 Description Use NLS API setting. 4 . Formatting Returns a Variant (String) containing an expression formatted according to instructions contained in a format expression. Syntax UCase(string) LCase(string) Remarks Only uppercase letters are converted to lowercase. Optional. Any valid expression. A valid named or user-defined format expression. Start with week in which January 1 occurs (default). Start with the first week that has at least four days in the year. Syntax Format(expression[. Optional. all lowercase letters and nonletter characters remain unchanged. firstdayofweek[. A constant that specifies the first day of the week. Optional. If string contains Null.Aaron Wirth LCase and UCase functions Returns a String that has been converted to lowercase.

1-355 100-9666 Example: MyTime and MyDate are displayed in the development environment using current system short time setting and short date setting. "<") ' Returns "hello". MyStr = Format(MyTime. "Long Time") ' Returns current system date in the system-defined long date format.00%".9.00%") ' Returns "500.IncludeLeadingDigit [. 5 . "##.UseParensForNegativeNumbers [. MyStr = Format(334. MyStr = Format(5459. ' User-defined formats. MyStr = Format(Date. a string is returned. FormatPercent. MyStr = Format(Time. ' Jan 27 1993".##0. "###0.00") ' Returns "5.IncludeLeadingDigit [.NumDigitsAfterDecimal [.4. Dim MyTime. MyDate.IncludeLeadingDigit [. ' If format is not supplied. ">") ' Returns "THIS IS IT".40". "hh:mm:ss AMPM") ' Returns "05:04:23 PM".NumDigitsAfterDecimal [.90".UseParensForNegativeNumbers [. "0.GroupDigits]]]]) Part Expression Description Required.UseParensForNegativeNumbers [. 1993# ' Returns current system time in the system-defined long time format. MyStr = Format(MyDate. "Long Date") MyStr = Format(MyTime. FormatNumber Syntax FormatCurrency(Expression[. MyStr = Format("This is it".459. mmm d yyyy") ' Returns "Wednesday.Aaron Wirth vbFirstFullWeek 3 Start with the first full week of the year. Symbol d dd ww mmm y yyyy Range 1-30 1-30 1-51 Displays full month names (Hijri month names have no abbreviations). "h:m:s") ' Returns "17:4:23". Expression to be formatted.GroupDigits]]]]) FormatNumber(Expression[. FormatCurrency.NumDigitsAfterDecimal [. MyStr MyTime = #17:04:23# MyDate = #January 27. MyStr = Format(23) ' Returns "23".00") ' Returns "334. MyStr = Format(5. MyStr = Format("HELLO".GroupDigits]]]]) FormatPercent(Expression[. "dddd.

display it as a long time. Tristate constant that indicates whether or not to place negative values within parentheses. 2) FormatDateTime Description Returns an expression formatted as a date or time. vbGeneralDate is used. See Settings section for values. Display a time using the time format specified in your computer's regional settings. Numeric value that indicates the date/time format used. Display a time using the 24-hour format (hh:mm).Aaron Wirth NumDigitsAfterDecimal Optional. See Settings section for values. If there is a date part. Optional. Display a date using the short date format specified in your computer's regional settings. Optional. See Settings section for values.45. Optional.45) result = FormatPercent(324. Numeric value indicating how many places to the right of the decimal are displayed. Optional. display it as a short date. Default value is –1. vbLongDate vbShortDate vbLongTime vbShortTime 1 2 3 4 6 . 0) result = FormatNumber(324. both parts are displayed. IncludeLeadingDigit UseParensForNegativeNumbers GroupDigits Example: result = FormatCurrency(324. If present.45. Display a date using the long date format specified in your computer's regional settings. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the computer's regional settings. If there is a time part. which indicates that the computer's regional settings are used. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. Date expression to be formatted.NamedFormat]) The FormatDateTime function syntax has these parts: Part Date NamedFormat Description Required. Settings The NamedFormat argument has the following settings: Constant vbGeneralDate 0 Value Description Display a date and/or time. Syntax FormatDateTime(Date[. If omitted.

Aaron Wirth Mid function
Returns a Variant (String) containing a specified number of characters from a string. To determine the number of characters in string, use the Len function. Syntax Mid(string, start[, length]) The Mid function syntax has these named arguments: Part string start length Description Required. String expression from which characters are returned. If string contains Null, Null is returned. Required; Long. Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string (""). Optional; Variant (Long). Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Example: Dim MyString, FirstWord, LastWord, MidWords MyString = "Mid Function Demo" ' Create text string. FirstWord = Mid(MyString, 1, 3) ' Returns "Mid". LastWord = Mid(MyString, 14, 4) ' Returns "Demo". MidWords = Mid(MyString, 5) ' Returns "Function Demo".

Chr Function
Returns a String containing the character associated with the specified character code. The required charcode argument is a Long that identifies a character. Syntax Chr(charcode) Example: Dim MyChar MyChar = Chr(65) MyChar = Chr(97) MyChar = Chr(62) MyChar = Chr(37)

' Returns A. ' Returns a. ' Returns >. ' Returns %.

Len Function
Returns a Long containing the number of characters in a string or the number of bytes required to store a variable. Syntax Len(string | varname) The Len function syntax has these parts: Part string Varname Description Any valid string expression. If string contains Null, Null is returned. Any valid variable name. If varname contains Null, Null is returned. If varname is a Variant, Len treats it the same as a String and always returns the number of characters it contains.

Example: Label1 = Len(Text1) ' Text1 = “Blah” ' Label1 = “4”

7

Aaron Wirth InStr function
Returns a Variant (Long) specifying the position of the first occurrence of one string within another. Syntax InStr([start, ]string1, string2[, compare]) The InStr function syntax has these arguments: Part start Description Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains Null, an error occurs. The start argument is required if compare is specified. Required. String expression being searched. Required. String expression sought. Optional. Specifies the type of string comparison. If compare is Null, an error occurs. If compare is omitted, the Option Compare setting determines the type of comparison. Specify a valid LCID (LocaleID) to use locale-specific rules in the comparison.

string1 string2 compare

Settings The compare argument settings are: Constant vbUseCompareOption vbBinaryCompare vbTextCompare vbDatabaseCompare Return Values If string1 is zero-length string1 is Null string2 is zero-length string2 is Null string2 is not found string2 is found within string1 start > string2 InStr returns 0 Null start Null 0 Position at which match is found 0 Value -1 0 1 2 Description Performs a comparison using the setting of the Option Compare statement. Performs a binary comparison. Performs a textual comparison. Microsoft Access only. Performs a comparison based on information in your database.

Example: Dim SearchString, SearchChar, MyPos SearchString ="XXpXXpXXPXXP" ' String to search in. SearchChar = "P" ' Search for "P". ' A textual comparison starting at position 4. Returns 6. MyPos = Instr(4, SearchString, SearchChar, 1) ' A binary comparison starting at position 1. Returns 9. MyPos = Instr(1, SearchString, SearchChar, 0) MyPos = Instr(SearchString, SearchChar) ' Returns 9.

8

Aaron Wirth
MyPos = Instr(1, SearchString, "W") ' Returns 0.

String function
Returns a Variant (String) containing a repeating character string of the length specified. Syntax String(number, character) The String function syntax has these named arguments: Part number character Description Required; Long. Length of the returned string. If number contains Null, Null is returned. Required; Variant. Character code specifying the character or string expression whose first character is used to build the return string. If character contains Null, Null is returned.

Remarks If you specify a number for character greater than 255, String converts the number to a valid character code using the formula: character Mod 256

InstrRev
Returns the position of an occurrence of one string within another, from the end of string. Syntax InstrRev(stringcheck, stringmatch[, start[, compare]]) Settings The compare argument can have the following values: Constant vbUseCompareOption vbBinaryCompare vbTextCompare vbDatabaseCompare Value –1 0 1 2 Description Performs a comparison using the setting of the Option Compare statement. Performs a binary comparison. Performs a textual comparison. Microsoft Access only. Performs a comparison based on information in your database.

Asc Function
Returns an Integer representing the character code corresponding to the first letter in a string. Syntax Asc(string) The required string argument is any valid string expression. If the string contains no characters, a run-time error occurs. Example: Dim MyNumber MyNumber = Asc("A") ' Returns 65. MyNumber = Asc("a") ' Returns 97. MyNumber = Asc("Apple") ' Returns 65.

Space Function
This function by itself produces a certain number of spaces. It's best use is to clear fixed-length strings. sRecord$ = Space(128)

9

an error occurs. 10 . If the compare argument is Null. count[. StrComp function Returns a Variant (Integer) indicating the result of a string comparison. LCID) The StrConv function syntax has these named arguments: Part string Description Required. MyStr2. MyComp = StrComp(MyStr1. Optional. conversion. MyStr1) ' Returns 1. If compare is omitted. Number of substring substitutions to perform. MyStr2. Specifies the type of string comparison. Position within expression where substring search is to begin. Syntax StrConv(string. Optional. 1 is assumed. MyComp = StrComp(MyStr2. which means make all possible substitutions. 1) ' Returns 0. Numeric value indicating the kind of comparison to use when evaluating substrings. 0) ' Returns -1. Substring being searched for. the Option Compare setting determines the type of comparison. String expression to be converted. Replacement substring. Syntax StrComp(string1. If omitted. Example: Dim MyStr1. Any valid string expression. MyComp = StrComp(MyStr1. Optional. replace[. Required. the default value is –1. StrConv function Returns a Variant (String) converted as specified. MyStr2. Required. String expression containing substring to replace. start[. find. See Settings section for values. Any valid string expression. Syntax Replace(expression. MyComp MyStr1 = "ABCD": MyStr2 = "abcd" ' Define variables. If omitted. compare]) The StrComp function syntax has these named arguments: Part string1 string2 compare Description Required.Aaron Wirth Replace Function Returns a string in which a specified substring has been replaced with another substring a specified number of times. Required. compare]]]) The Replace function syntax has these named arguments: Part expression find replace start count compare Description Required. Optional. string2[.

Aaron Wirth conversion LCID Required.) 11 . The sum of values specifying the type of conversion to perform. (The system LocaleID is the default. Optional. The LocaleID. Integer. if different than the system LocaleID.

Aaron Wirth Math Val function Returns the numbers contained in a string as a numeric value of appropriate type. Randomize uses number to initialize the Rnd function's random-number generator. Round Description Returns a number rounded to a specified number of decimal places. Syntax Randomize [number] Rnd[(number)] Example: Randomize Label1 = Int((6 * Rnd) + 1) 'Generate random value between 1 and 6. integers are returned by the Round function. Both Int and Fix remove the fractional part of number and return the resulting integer value. the function recognizes the radix prefixes &O (for octal) and &H (for hexadecimal).4 to -9. and linefeed characters are stripped from the argument.numdecimalplaces]) The Round function syntax has these parts: Part expression numdecimalplaces Description Required. Rnd and Randomize functions A function which generates a random number. Syntax Round(expression [. The Val function stops reading the string at the first character it can't recognize as part of a number. such as dollar signs and commas. Syntax Val(string) The required string argument is any valid string expression. Numeric expression being rounded. and Fix converts -8. are not recognized. Int returns the first negative integer less than or equal to number.Text = Number Round(Number. The difference between Int and Fix is that if number is negative. Blanks. giving it a new seed value. If number contains Null. Optional.5) ‘Rounds the number in text1 to 5 decimal places Int and Fix functions Returns the integer portion of a number. Null is returned. Symbols and characters that are often considered parts of numeric values. Number indicating how many places to the right of the decimal are included in the rounding. Int converts -8. tabs. If omitted.4 to -8. However. 12 . Syntax Int(number) Fix(number) The required number argument is a Double or any valid numeric expression. Example: Text1. If you omit number. whereas Fix returns the first negative integer greater than or equal to number. the value returned by the system timer is used as the new seed value. For example.

MySign MyVar1 = 12: MyVar2 = -2. Syntax Sin(number) Cos(number) Tan(number) Log(number) Atn(number) Exp(number) Abs function Returns a value of the same type that is passed to it specifying the absolute value of a number. you're all set there too. MyVar3. Syntax Abs(number) The required number argument can be any valid numeric expression.4: MyVar3 = 0 MySign = Sgn(MyVar1) ' Returns 1. If number contains Null. Cos. Log.Aaron Wirth Sgn function Returns a Variant (Integer) indicating the sign of a number. Null is returned. Syntax Sgn(number) The required number argument can be any valid numeric expression. From the list of VB functions below. MySign = Sgn(MyVar2) ' Returns -1. you can make any geometric calculation that exists. Example: Dim MyNumber MyNumber = Abs(50. Return Values If number is Greater than zero Equal to zero Less than zero Sgn returns 1 0 -1 Example: Dim MyVar1.3. MyNumber = Abs(-50. MySign = Sgn(MyVar3) ' Returns 0. zero is returned. MyVar2.3) ' Returns 50. (Assuming you're Albert Einstein).3) ' Returns 50. 13 . if it is an uninitialized variable. Atn & Exp Functions If you're into geometry. Tan.3. Sin.

1)) + (Sgn(X) – 1) * (2 * Atn(1)) Arccotan(X) = Atn(X) + 2 * Atn(1) HSin(X) = (Exp(X) – Exp(-X)) / 2 HCos(X) = (Exp(X) + Exp(-X)) / 2 HTan(X) = (Exp(X) – Exp(-X)) / (Exp(X) + Exp(-X)) HSec(X) = 2 / (Exp(X) + Exp(-X)) HCosec(X) = 2 / (Exp(X) – Exp(-X)) HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) – Exp(-X)) HArcsin(X) = Log(X + Sqr(X * X + 1)) HArccos(X) = Log(X + Sqr(X * X – 1)) HArctan(X) = Log((1 + X) / (1 – X)) / 2 HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X) HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) + 1) / X) HArccotan(X) = Log((X + 1) / (X – 1)) / 2 LogN(X) = Log(X) / Log(N) 14 .Aaron Wirth Other Math Functions The following is a list of nonintrinsic math functions that can be derived from the intrinsic math functions: Function Secant Cosecant Cotangent Inverse Sine Inverse Cosine Inverse Secant Inverse Cosecant Inverse Cotangent Hyperbolic Sine Hyperbolic Cosine Hyperbolic Tangent Hyperbolic Secant Hyperbolic Cosecant Hyperbolic Cotangent Inverse Hyperbolic Sine Inverse Hyperbolic Cosine Inverse Hyperbolic Tangent Inverse Hyperbolic Secant Inverse Hyperbolic Cosecant Inverse Hyperbolic Cotangent Logarithm to base N Derived equivalents Sec(X) = 1 / Cos(X) Cosec(X) = 1 / Sin(X) Cotan(X) = 1 / Tan(X) Arcsin(X) = Atn(X / Sqr(-X * X + 1)) Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1) Arcsec(X) = Atn(X / Sqr(X * X – 1)) + Sgn((X) – 1) * (2 * Atn(1)) Arccosec(X) = Atn(X / Sqr(X * X .

any numeric variable. MyResult = 10 Mod 3 ' Returns 1. A (result) equals 5. any numeric expression. Required. MyResult = 12.7 Example: Dim MyResult MyResult = 10 Mod 5 ' Returns 0. If either expression evaluates to False. operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result.3 ' Returns 0. Remarks The modulus. MyResult = 12 Mod 4. any expression. any numeric expression. Required.. in the following expression. For example. A = 19 Mod 6. result is True. And Operator Used to perform a logical conjunction on two expressions. Remarks If both expressions evaluate to True. The following table illustrates how result is determined: If expression1 is True True True False False False Null And expression2 is True False Null True False Null True The result is True False Null False False False Null 15 . any expression. or remainder. Required.Aaron Wirth Logic Mod Operator Syntax result = number1 Mod number2 The Mod operator syntax has these parts: Part result number1 number2 Description Required. result is False. Required. any numeric variable.6 Mod 5 ' Returns 3. Syntax result = expression1 And expression2 The And operator syntax has these parts: Part result expression1 expression2 Description Required.

result is True. Syntax result = expression1 Or expression2 The Or operator syntax has these parts: Part result expression1 expression2 Description Required. Or Operator Used to perform a logical disjunction on two expressions. B. MyCheck = A > B And B > C ' Returns True. 16 . Required. MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. D. MyCheck A = 10: B = 8: C = 6: D = Null ' Initialize variables. MyCheck = B > D Or B > A ' Returns Null. any expression. MyCheck = A > B And B > D ' Returns Null. MyCheck = B > A Or B > C ' Returns True. The following table illustrates how result is determined: If expression1 is True True True False False False Null Null Null And expression2 is True False Null True False Null True False Null Then result is True True True True False Null True Null Null Example: Dim A. C. C. MyCheck = A > B Or B > C ' Returns True. MyCheck = B > A And B > C ' Returns False. any numeric variable. B. Remarks If either or both expressions evaluate to True. any expression.Aaron Wirth Null Null False Null False Null Example: Dim A. MyCheck = A > B Or B > D ' Returns True. Required. D.

if either expression is Null. ' Returns False. result is determined according to the following table: If expression1 is True True False False And expression2 is True False True False Then result is False True True False Example: Dim A. any string expression. Example: Dim Done As Boolean Done = True If Not Done Then LetsFinish The LetsFinish procedure will not run. Syntax result = string Like pattern The Like operator syntax has these parts: Part result string pattern Description Required. any numeric variable. the code segment will run if a condition is False. Required. Remarks If one. result is True. 17 . Required. ' Returns False. However. any expression. Required. any numeric variable. Required. Like operator Used to compare two strings. B. MyCheck A = 10: B = 8: C = 6: D = Null MyCheck = A > B Xor B > C MyCheck = B > A Xor B > C MyCheck = B > A Xor C > B MyCheck = B > D Xor A > B ' Initialize variables. When neither expression is Null. of the expressions evaluates to True. any expression. and only one. ' Returns Null. D. If Not Done is equivalent to If Done = False and If Done is the same as If Done = True. any string expression conforming to the pattern-matching conventions described in Remarks. C. If Not If Not is the exact opposite of If. Syntax [result =] expression1 Xor expression2 The Xor operator syntax has these parts: Part result expression1 expression2 Description Optional. ' Returns True.Aaron Wirth Xor Operator Used to perform a logical exclusion on two expressions. result is also Null. Notice we just used the boolean variable by itself.

Two variables can be made to refer to the same object in several ways. if they do not. Remarks If object1 and object2 both refer to the same object. Example: MyCheck = YourObject Is ThisObject ' Returns True. The behavior of the Like operator depends on the Option Compare statement. any object name. Any single character in charlist. result is True. result is True. Any single digit (0–9). Required. Zero or more characters. to match strings. Required. The following table shows the characters allowed in pattern and what they match: Characters in pattern ? * # [charlist] [!charlist] Matches in string Any single character. MyCheck = ThatObject Is ThisObject ' Returns False. 18 . If either string or pattern is Null.Aaron Wirth Remarks If string matches pattern. The pattern-matching features allow you to use wildcard characters. any object name. The default string-comparison method for each module is Option Compare Binary. Built-in pattern matching provides a versatile tool for string comparisons. in any combination. if there is no match. Syntax result = object1 Is object2 The Is operator syntax has these parts: Part result object1 object2 Description Required. result is Null. Example: Dim Name As String Name = InputBox("Enter your name") Find out if user's name begins with a J If sName$ Like "J*" Then (code segment) End If Is Operator Used to compare two object reference variables. Any single character not in charlist. result is False. or character ranges. character lists. any numeric variable. result is False.

and "" for strings). Sets each element as if it were a separate variable. . Name of the variable. Example: Erase sMessage In a regular array. follows standard variable naming conventions.Aaron Wirth Arrays Erase statement Reinitializes the elements of fixed-size arrays and releases dynamic-array storage space. (False for Boolean. the Erase statement will simply initialize all the elements. Erase sets the elements of a fixed array as follows: Type of Array Fixed numeric array Fixed string array (variable length) Fixed string array (fixed length) Fixed Variant array Array of user-defined types Array of objects Effect of Erase on Fixed-Array Elements Sets each element to zero. . Remarks Erase behaves differently depending on whether an array is fixed-size (ordinary) or dynamic. 0 for numbers. Sets each element to the special value Nothing. Example: Dim Word As String ReDim Used at procedure level to reallocate storage space for dynamic array variables. The subscripts argument uses the following syntax: [lower To] upper [. Required. Sets each element to a zero-length string (""). Dim Dim statement placed right in the procedure where it's going to be used. the variable is destroyed and memory allocated to the variable is released.[lower To] upper] . When the procedure finishes (End Sub or End Function). Dimensions of an array variable. Sets each element to zero. Sets each element to Empty. . When not explicitly stated in lower. . up to 60 multiple dimensions may be declared. varname(subscripts) [As type]] . Syntax Erase arraylist The required arraylist argument is one or more comma-delimited array variables to be erased. 19 . Required. The lower bound is zero if no Option Base statement is present. Keyword used to preserve the data in an existing array when you change the size of the last dimension. the lower bound of an array is controlled by the Option Base statement. In a dynamic array. The ReDim statement syntax has these parts: Part Preserve varname subscripts Description Optional. The value of a procedure level variable cannot be accessed outside it's procedure. Erase recovers no memory for fixed-size arrays. Syntax ReDim [Preserve] varname(subscripts) [As type] [. Erase will also release all the memory allocated to the array.

Decimal (not currently supported). 10. For a Variant containing an array. type describes the type of each element of the array. Integer. String * length (for fixed-length strings). the first statement creates a variable named A as a Variant. an array of zero length is created. In the following example. String (for variable-length strings). Double. "Thu". a user-defined type. MyDay = MyWeek(4) ' MyDay contains "Thu". "Tue". Object. Currency. Date. 10. 10) [Code] ReDim Preserve X(10. MyDay = MyWeek(2) ' MyDay contains "Tue". "Sun") ' Return values assume lower bound set to 1 (using Option Base ' statement). Remarks The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private. If no arguments are specified. Remarks The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element. The last statement assigns the value contained in the second array element to another variable. or an object type. but doesn't change the Variant to some other type. "Wed". 20 . "Fri". Example: Dim X(10. "Sat". Data type of the variable. may be Byte. Boolean. Long. Example: Dim MyWeek. Use a separate As type clause for each variable being defined. Syntax Array(arglist) The required arglist argument is a comma-delimited list of values that are assigned to the elements of the array contained within the Variant. The second statement assigns an array to variable A.Aaron Wirth type Optional. 15) Array Function Returns a Variant containing an array. Single. or Dim statement with empty parentheses (without dimension subscripts). MyDay MyWeek = Array("Mon". Variant. Public.

Optional. or the volume label of a drive. vbVolume is ignored. Available only on the Macintosh. Settings The attributes argument settings are: Constant vbNormal vbReadOnly vbHidden VbSystem vbVolume Value 0 1 2 4 8 Description (Default) Specifies files with no attributes. or folder that matches a specified pattern or file attribute. A zero-length string ("") is returned if pathname is not found. attributes])] The Dir function syntax has these parts: Part pathname attributes Description Optional.ini" Then MsgBox "File exists" Else MsgBox "File does not exist" End If 21 . whose sum specifies file attributes. Not available on the Macintosh.Aaron Wirth Files/Folders Dir Returns a String representing the name of a file. Syntax Dir[(pathname[. Specifies directories or folders in addition to files with no attributes. Example: If Dir("c:\windows\win. Specified file name is an alias. vbDirectory vbAlias 16 64 Note These constants are specified by Visual Basic for Applications and can be used anywhere in your code in place of the actual values. and drive. if any other attributed is specified. returns files that match pathname but have no attributes. Not available on the Macintosh. Constant or numeric expression. Specifies hidden files in addition to files with no attributes. String expression that specifies a file name — may include directory or folder. If omitted. Specifies read-only files in addition to files with no attributes. Specifies volume label. Specifies system files in addition to files with no attributes.ini") = "win. directory.

Aaron Wirth ChDir Changes the current directory or folder. If no drive is specified. MkDir Creates a new directory or folder. MkDir creates the new directory or folder on the current drive. if the default drive is C. Syntax ChDrive drive The required drive argument is a string expression that specifies an existing drive. Remarks The ChDir statement changes the default directory but not the default drive. Example: ‘Creates a folder called ‘New Folder’ MkDir “C:\New Folder” 22 . If the drive argument is a multiple-character string. MyPath = CurDir("D") ' Returns "D:\EXCEL". the current drive doesn't change. the following statement changes the default directory on drive D. On the Macintosh. Example: ' Assume current path on C drive is "C:\WINDOWS\SYSTEM" (on Microsoft Windows). Example: ChDrive "D" ' Make "D" the current drive. CurDir Returns a Variant (String) representing the current path. ChDrive uses only the first letter. MyPath = CurDir("C") ' Returns "C:\WINDOWS\SYSTEM". ' Assume C is the current drive. For example. CurDir ignores any drive specified and simply returns the path for the current drive. Syntax MkDir path The required path argument is a string expression that identifies the directory or folder to be created. Example: Dim Path as string Dir(“C:\NewFolder”) = Path Path = ChDir(“C:\MyFolder”) ChDrive Changes the current drive. CurDir returns the path for the current drive. but C remains the default drive. If no drive is specified. If you supply a zero-length string (""). ChDir changes the default directory or folder on the current drive. Syntax ChDir path The required path argument is a string expression that identifies which directory or folder becomes the new default directory or folder. Syntax CurDir[(drive)] The optional drive argument is a string expression that specifies an existing drive. The path may include the drive. The path may include the drive. If no drive is specified or if drive is a zero-length string (""). Dim MyPath MyPath = CurDir ' Returns "C:\WINDOWS\SYSTEM". ' Assume current path on D drive is "D:\EXCEL".

and the drive.Aaron Wirth RmDir Function Removes an existing directory or folder. MyStamp = FileDateTime "c:\Blah. Syntax FileLen(pathname) The required pathname argument is a string expression that specifies a file. Note To obtain the length of an open file. FileLen Returns a Long specifying the length of a file in bytes. the value returned represents the size of the file immediately before it was opened. use the LOF function.txt” FileDateTime Returns a Variant (Date) that indicates the date and time when a file was created or last modified. The pathname may include the directory or folder. The pathname may include the directory or folder. Use the Kill statement to delete all files before attempting to remove a directory or folder. 23 . Syntax Kill pathname The required pathname argument is a string expression that specifies one or more file names to be deleted. and the drive. Remarks If the specified file is open when the FileLen function is called. The path may include the drive. Remarks An error occurs if you try to use RmDir on a directory or folder containing files. Example: Dim Size Size = FileLen("TESTFILE") ' Returns file length (bytes). Example: Dim MyStamp ' Assume TESTFILE was last modified on September 2. RmDir removes the directory or folder on the current drive. Example: Kill "c:\Blah. If no drive is specified. 2005 at 4:00:00 PM.txt” ' Returns "2/9/05 4:00:00 PM". The pathname may include the directory or folder. Syntax FileDateTime(pathname) The required pathname argument is a string expression that specifies a file name. Syntax RmDir path The required path argument is a string expression that identifies the directory or folder to be removed. and the drive. Example: RmDir "c:\windows\pictures" Kill Function Deletes files from a disk.

an error occurs. Setting up menu items for cut. The destination may include directory or folder. Syntax FileCopy source.Clear Clipboard.SetText txtMain. directory. Remarks If you try to use the FileCopy statement on a currently open file. String expression that specifies the name of the file to be copied.Aaron Wirth FileCopy Copies a file. Copy & Pasting Text The Clipboard object represents the Windows clipboard which is available to all running applications. Required. and drive. Example: Private Sub mnuCopy_Click( ) Clipboard. String expression that specifies the target file name.SetText txtMain. copy. Directory or folder.GetText End Sub GetAttr Returns an Integer representing the attributes of a file. Return Values The value returned by GetAttr is the sum of the following attribute values: Constant vbNormal vbReadOnly vbHidden vbSystem vbDirectory Value 0 1 2 4 16 Description Normal. The source may include directory or folder. Read-only. or folder.Clear Clipboard. 24 . The pathname may include the directory or folder.SelText = "" End Sub Private Sub mnuPaste_Click( ) txtMain.SelText = Clipboard. Not available on the Macintosh. destination The FileCopy statement syntax has these named arguments: Part source destination Description Required. Syntax GetAttr(pathname) The required pathname argument is a string expression that specifies a file name. Hidden. and pasting from and into one TextBox is fairly simple.SelText End Sub Private Sub mnuCut_Click( ) Clipboard. System file.SelText txtMain. and drive. Cut. and the drive. therefore you can allow your users to place text or pictures on the Clipboard and paste them anywhere they like.

The names can be used anywhere in your code in place of the actual values. Open "TEST" & MyIndex For Output As #FileNumber Write #FileNumber. "This is a sample. Read-only. Close #FileNumber ' Close file. 25 .Aaron Wirth vbArchive vbAlias 32 64 File has changed since last backup. Next MyIndex ' Create file name. attributes The SetAttr statement syntax has these named arguments: Part pathname attributes Description Required. FreeFile function Returns an Integer representing the next file number available for use by the Open statement. Syntax SetAttr pathname. Hidden. FileNumber For MyIndex = 1 To 5 ' Loop 5 times. FileNumber = FreeFile ' Get unused file ' number. inclusive. SetAttr Sets attribute information for a file. Not available on the Macintosh. Required. Available only on the Macintosh. Not available on the Macintosh. Specify a 1 to return a file number in the range 256 – 511. Specified file name is an alias. String expression that specifies a file name — may include directory or folder. Available only on the Macintosh. Constant or numeric expression. Note These constants are specified by Visual Basic for Applications. whose sum specifies file attributes. Settings The attributes argument settings are: Constant vbNormal vbReadOnly vbHidden vbSystem vbArchive vbAlias Value 0 1 2 4 32 64 Description Normal (default). File has changed since last backup. Specified file name is an alias. and drive. Example: Dim MyIndex. System file. Specify a 0 (default) to return a file number in the range 1 – 255. Syntax FreeFile[(rangenumber)] The optional rangenumber argument is a Variant that specifies the range from which the next free file number is to be returned. Remarks Use FreeFile to supply a file number that is not already in use." ' Output text.

Important In Binary. Write. it is created when a file is opened for Append. Keyword specifying the file mode: Append. A valid file number in the range 1 to 511. and drive. you can open a file using a different file number without first closing the file. Append: use this to write something into the file but keep what is already in the file. The Len clause is ignored if mode is Binary. Example: Open “a:\gordon. Input. the Open operation fails and an error occurs. Optional. Text1. this value is the record length. Keyword specifying the operations restricted on the open file by other processes: Shared. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer. and Random modes. Binary. Required.txt” For Output As #1 Print #1. inclusive. Number less than or equal to 32. Input: use this to open and read a file. Lock Write. Input. or Read Write.Aaron Wirth Open Function Enables input/output (I/O) to a file. For files opened for random access. Required. If the file specified by pathname doesn't exist. Binary: use this for binary access files Random: use this for random access files You must open a file before any I/O operation can be performed on it. Keyword specifying the operations permitted on the open file: Read. or Random. Output. Remarks Output: use the print statement to print something in a file. For sequential files. you must close a file before opening it with a different file number. the file is opened for Random access. Optional. Syntax Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength] The Open statement syntax has these parts: Part pathname mode access lock filenumber reclength Description Required. In Append and Output modes. Lock Read. and Lock Read Write. Binary.Text ‘prints Text1 into the file Close #1 26 . or Random modes. this value is the number of characters buffered. If unspecified. String expression that specifies a file name — may include directory or folder. Output.767 (bytes). Optional. Use the FreeFile function to obtain the next available file number. If the file is already opened by another process and the specified type of access is not allowed.

. Remarks Data read with Line Input # is usually written from a file with Print #. templine Text1. All buffer space associated with the closed file is released.Aaron Wirth Close Statement Concludes input/output (I/O) to a file opened using the Open statement. Syntax EOF(filenumber) The required filenumber argument is an Integer containing any valid file number. When the Close statement is executed. With files opened for Random or Binary access. Syntax Line Input #filenumber. Close #1 EOF Function Returns an Integer containing the Boolean value True when the end of a file opened for Random or sequential Input has been reached.txt” For Input As 1 Do Until EOF(1) Line Input #1. an attempt to read through the file using the Input function until EOF returns True generates an error.text + templine Loop Close #1 27 .txt” For Input As #1 Line Input #1. Syntax Close [filenumberlist] The optional filenumberlist argument can be one or more file numbers using the following syntax.Text = text1. The EOF function returns False until the end of the file has been reached. [#]filenumber] . . When you close files that were opened for Output or Append. Example: Open “a:\gordon. where filenumber is any valid file number: [[#]filenumber] [. Line Input Reads a single line from an open sequential file and assigns it to a String variable. all active files opened by the Open statement are closed. Remarks If you omit filenumberlist. Any valid file number. TextLine ' Read line into variable. Remarks Use EOF to avoid the error generated by attempting to get input past the end of a file. EOF always returns True. the final buffer of output is written to the operating system buffer for that file. Required. EOF returns False until the last executed Get statement is unable to read an entire record. Example: dim templine as string Open “a:\ratbag. Valid Variant or String variable name. varname The Line Input # statement syntax has these parts: Part filenumber varname Description Required. the association of a file with its file number ends. or use Get when using the EOF function. With files opened for Output. Use the LOF and Loc functions instead of EOF when reading binary files with Input. With files opened for Binary access.

Blah" + Text1. Optional. [outputlist] The Print # statement syntax has these parts: Part filenumber outputlist Description Required. Remarks Data written with Print # is usually read from a file with Line Input # or Input.txt" For Output As #1 Print #1. Expression or list of expressions to print. in bytes. Print Function Writes display-formatted data to a sequential file.Aaron Wirth Lof Function Returns a Long representing the size. FileLength = LOF(1) ' Get length of file.Path & "\myFile. Example: Open App. Syntax LOF(filenumber) The required filenumber argument is an Integer containing a valid file number. Any valid file number. Example: Dim FileLength Open "TESTFILE" For Input As #1 ' Open file. Close #1 ' Close file. Note Use the FileLen function to obtain the length of a file that is not open.Text Close #1 28 . of a file opened using the Open statement. "Blah. Syntax Print #filenumber.

On Error Resume Next On Error GoTo 0 Remarks If you don't use an On Error statement. Execution resumes at line specified in the required line argument. execution resumes with the statement that caused the error. If the error occurred in a called procedure. that is. The line argument is a line label or line number and must be in the same procedure as the error handler. If the error occurred in the same procedure as the error handler. Resume Line () Resumes execution after an error-handling routine is finished. making the error handler active. control branches to line. can also be used to disable an error-handling routine. The specified line must be in the same procedure as the On Error statement. Resume. Disables any enabled error handler in the current procedure. 29 . The line argument is any line label or line number. Syntax Resume [0] Resume Next Resume line The Resume statement syntax can have any of the following forms: Statement Resume Description If the error occurred in the same procedure as the error handler. an error occurs. execution resumes with the statement immediately following the statement that last called out of the procedure containing the error-handling routine (or On Error Resume Next statement). If the error occurred in a called procedure. Specifies that when a run-time error occurs. Use this form rather than On Error GoTo when accessing objects. Syntax On Error GoTo line On Error Resume Next On Error GoTo 0 The On Error statement syntax can have any of the following forms: Statement On Error GoTo line Description Enables the error-handling routine that starts at line specified in the required line argument. any run-time error that occurs is fatal. Resume Next Resume line Remarks If you use a Resume statement anywhere except in an error-handling routine. If a runtime error occurs. control goes to the statement immediately following the statement where the error occurred where execution continues. otherwise. execution resumes with the statement immediately following the statement that caused the error. Resume Next. an error message is displayed and execution stops.Aaron Wirth Error Handling On Error Statement Enables an error-handling routine and specifies the location of the routine within a procedure. execution resumes at the statement that last called out of the procedure containing the error-handling routine. a compile-time error occurs.

In new code. If the string doesn't exist. 30 . Can be any valid error number. Description contains a zero-length string (""). Name of the current Visual Basic project. Error 11 ' Simulate the "Division by zero" error. Remarks The Error statement is supported for backward compatibility. path. and file name of the appropriate Visual Basic Help file. The appropriate Visual Basic Help file context ID for the error corresponding to the Number property. use the Err object's Raise method to generate run-time errors. HelpFile HelpContext LastDLLError Example: On Error Resume Next ' Defer error handling.Aaron Wirth Example: Private Sub … On Error GoTo Error End Sub Error: … Resume Error Function Simulates the occurrence of an error. especially when creating objects. if this string exists. The fully qualified drive. If errornumber is defined. the Error statement calls the error handler after the properties of Err object are assigned the following default values: Property Number Source Description Value Value specified as argument to Error statement. String expression corresponding to the return value of the Error function for the specified Number. Syntax Error errornumber The required errornumber can be any valid error number. Zero.

Optional. Indicates that the Function procedure is accessible to all other procedures in all modules. Date. Private Friend Static name arglist type statements expression The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] Part Optional Description Optional. all subsequent arguments in arglist must also be optional and declared using the Optional keyword. ByRef. Decimal (not currently supported). List of variables representing arguments that are passed to the Function procedure when it is called. Return value of the Function. ByVal ByRef ParamArray 31 . the procedure is not available outside the project. Boolean. String. If used. Indicates that an argument is not required. Optional. Variant. Required. follows standard variable naming conventions. Optional. Syntax [Public | Private | Friend] [Static] Function name [(arglist)] [As type] [statements] [name = expression] [Exit Function] [statements] [name = expression] End Function The Function statement syntax has these parts: Part Public Description Optional. arguments. Optional. Double. Data type of the value returned by the Function procedure. Used only in a class module. Multiple variables are separated by commas. If used in a module that contains an Option Private. Optional. Optional. or any user-defined type.Aaron Wirth Declarations Function Procedures Declares the name. Optional can't be used for any argument if ParamArray is used. may be Byte. ByRef is the default in Visual Basic. Name of the Function. and code that form the body of a Function procedure. Any group of statements to be executed within the Function procedure. It may not be used with ByVal. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. Indicates that the Function procedure is visible throughout the project. Single. Optional. Indicates that the argument is passed by reference. Optional. The Static attribute doesn't affect variables that are declared outside the Function. Indicates that the argument is passed by value. Currency. Object. Optional. even if they are used in the procedure. The ParamArray keyword allows you to provide an arbitrary number of arguments. Indicates that the Function procedure is accessible only to other procedures in the module where it is declared. Integer. Optional. Indicates that the Function procedure's local variables are preserved between calls. Long. or Optional. or (except fixed length). but not visible to a controller of an instance of an object.

Data type of the constant. may be Byte. Data type of the argument passed to the procedure. A Friend procedure does't appear in the type library of its parent class. Optional. Optional. Boolean. If the parameter is not Optional. follows standard variable naming conventions. however. or any combination that includes all arithmetic or logical operators except Is. Long. follows standard variable naming conventions. Single. Literal. Public Const MyString = "HELP" ' Declare Private Integer constant. Keyword used at module level to declare constants that are available to all procedures in all modules. Long. other constant. Required. String. Decimal (not currently supported) Date. The Friend keyword can only be used in class modules. Optional. Private Const MyInt As Integer = 5 ' Declare multiple constants on same line. Not allowed in procedures. expression Remarks Constants are private by default. Any constant or constant expression. Currency. Keyword used at module level to declare constants that are available only within the module where the declaration is made. Private. the default visibility of module-level constants can be changed using the Public keyword. Valid for Optional parameters only. or Variant. constants are always private. Syntax [Public | Private] Const constname [As type] = expression The Const statement syntax has these parts: Part Public Private constname type Description Optional. or Friend. String (variable length only). or a specific object type. Double. Object. Integer. Not allowed in procedures. Variant. Use a separate As type clause for each constant being declared. MyDouble As Double = 3. defaultvalue Remarks If not explicitly specified using Public. Name of the variable representing the argument. Friend procedures can be accessed by procedures in any module of a project. Name of the constant. Example: ' Constants are Private by default.Aaron Wirth varname type Required.4567 32 . Double. may be Byte. an explicit default value can only be Nothing. the value of local variables is not preserved between calls. nor can a Friend procedure be late bound. Single. Const MyVar = 459 ' Declare Public constant. However. In standard modules. Integer. Required. Decimal (not currently supported). Currency. In class modules. Boolean. If Static isn't used. Within procedures. a user-defined type may also be specified. Const MyStr = "Hello". Optional. Const Declares constants for use in place of literal values. constants can only be private and their visibility can't be changed using the Public keyword. Function procedures are public by default. their visibility can't be changed. Date. If the type is an Object.

CallByName Executes a method of an object. Name of the procedure to call. However.Aaron Wirth Call Statement Transfers control to a Sub procedure. argumentlist must be enclosed in parentheses. A constant of type vbCallType representing the type of procedure being called. Example: 33 . Optional: Variant (Array). if you use the Call keyword to call a procedure that requires arguments. Remarks The CallByName function is used to get or set a property. If specified. A string expression containing the name of a property or method of the object. The return value of the function is ' discarded. ByVal and ByRef can be used with Call when making a call to a Macintosh code resource. Function procedure. Comma-delimited list of variables. Variant (Object). Syntax CallByName(object. Syntax [Call] name [argumentlist] The Call statement syntax has these parts: Part Call Description Optional. On the Macintosh. Constant. Optional. you must enclose argumentlist in parentheses. Required. Variant (String). or dynamic-link library (DLL) procedure.[args()]) The CallByName function syntax has these named arguments: Part object procname calltype args() Description Required. Example: Call an intrinsic function. keyword. ByVal and ByRef can be used with Call only when calling a DLL procedure. Remarks You are not required to use the Call keyword when calling a procedure. or sets or returns a property of an object. arrays. Required. 1) ' AppName contains the path of the ' executable file. Components of argumentlist may include the keywords ByVal or ByRef to describe how the arguments are treated by the called procedure. procname. However. or expressions to pass to the procedure. or invoke a method at run time using a string name. For example: Call MyProc(0) name argumentlist Required. calltype. Call Shell(AppName. The name of the object on which the function will be executed.

and userdefined types declared at module level. the public parts. variables. Syntax Option Compare {Binary | Text | Database} Remarks If used. sort order is determined by the code page. 100. Example: Option explicit ' Force explicit variable declaration. If you don't use the Option Explicit statement. Syntax Option Explicit Remarks If used. vbMethod. Text. objects. Private. "MousePointer". the Option Private statement must appear at module level. but they are not available to other applications or projects. for example. Option Private When used in host applications that allow references across multiple projects. Option Private has no effect. 100 Option Explicit Used at module level to force explicit declaration of all variables in that module. the Option Explicit statement must appear in a module before any procedures. for example. standalone versions of Visual Basic. the Option Compare statement must appear in a module before any procedures. When the same characters are sorted using Option Compare Text. A typical binary sort order is shown in the following example: A<B<E<Z<a<b<e<z<À<Ê<Ø<à<ê<ø Option Compare Text results in string comparisons based on a case-insensitive text sort order determined by your system's locale. Example: Option private Module ' Indicates that module is private. Public. MyVar = 10 ' Declared variable does not generate error. ReDim. the default text comparison method is Binary. Dim MyVar ' Declare variable. MyInt = 10 ' Undeclared variable generates error. When a module contains Option Private Module. "Move". In host applications that don’t permit such references. Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. If you attempt to use an undeclared variable name. an error occurs at compile time. When Option Explicit appears in a module. or Static statements. Option Compare Used at module level to declare the default comparison method to use when string data is compared. The Option Compare statement specifies the string comparison method (Binary. or Database) for a module. vbLet. vbCrosshair Result = CallByName (Text1. you must explicitly declare all variables using the Dim. all undeclared variables are of Variant type unless the default type is otherwise specified with a Deftype statement. "MousePointer". If a module doesn't include an Option Compare statement. In Microsoft Windows. Option Private Module prevents a module’s contents from being referenced outside its project. Syntax Option Private Module Remarks If used. before any procedures. are still available within the project containing the module. vbGet) CallByName Text1. 34 . the following text sort order is produced: (A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø) Example: Set the string comparison method to Binary.Aaron Wirth CallByName Text1.

Object. ' Set the string comparison method to Text. Required.Aaron Wirth Option compare Binary ' That is. you can declare a variable of that type anywhere within the scope of the declaration. Single. When not explicitly stated in lower. Example: Type StateData CityCode (1 To 100) As Integer County As String * 30 End Type ' Declare a static array. follows standard variable naming conventions. Syntax GetObject([pathname] [. "AAA" is equal to "aaa". except that keywords can be used. Used to declare user-defined htypes that are available to all procedures in all modules in all projects. Boolean. Syntax [Private | Public] Type varname elementname [([subscripts])] As type [elementname [([subscripts])] As type] . Double. Long. class]) The GetObject function syntax has these named arguments: Part Description 35 . Once you have declared a user-defined type using the Type statement. ReDim. Type…End Type Used at module level to define a user-defined data thype containing one or more elements.. may be Byte. Name of the user-defined type. Required. the lower bound of an array is controlled by the Option Base statement. "AAA" is less than "aaa". String (for variable-length strings). another userdefined type. Element names also follow standard variable naming conventions. Public. Data type of the element. Optional. Variant. Private. End Type The Type statement syntax has these parts: Part Public Private varname elementname subscripts Description Optional. or an object type. String * length (for fixed-length strings). Dim Washington(1 To 100) As StateData GetObject Returns a reference to an object provided by an ActiveX component. Currency. Use Dim. The lower bound is zero if no Option Base statement is present. Option compare Text ' That is. Name of an element of the user-defined type. Required. Date. Used to declare user-defined types that are available only within the module where the declaration is made. Integer.. type Remarks The Type statement can be used only at module level. Decimal (not currently supported). or Static to declare a variable of a user-defined type.

Example: Dim ExcelSheet As Object Set ExcelSheet = CreateObject("Excel. Variant (String).objecttype and has these parts: Part appname objecttype Description Required. Optional. Required. The name of the application providing the object. a Document object.Aaron Wirth pathname class Optional. A string representing the class of the object. Required. Optional. Variant (String). The class argument uses the syntax appname. and a Toolbar object. class is required. Remarks Use the GetObject function to access an ActiveX object from a file and assign the object to an object variable. Variant (String). For example.CAD") CreateObject Creates and returns a reference to an ActiveX object. The name of the application providing the object. Variant (String). The full path and name of the file containing the object to retrieve. Syntax [Let] varname = expression The Let statement syntax has these parts: Part Description 36 . Use the Set statement to assign the object returned by GetObject to the object variable. The type or class of object to create.[servername]) The CreateObject function syntax has these parts: Part class servername Description Required.Sheet") Let Statement Assigns the value of an expression to a variable or property. The class argument uses the syntax appname. Example: Dim CADObject As Object Set CADObject = GetObject("C:\CAD\SCHEMA. Variant (String). Variant (String).objecttype and has these parts: Part appname objecttype Description Required. The application name and class of the object to create. a word processing application may provide an Application object. If pathname is omitted. If servername is an empty string (""). Variant (String). Remarks Every application that supports Automation provides at least one type of object. The type or class of object to create. Syntax CreateObject(class. the local machine is used. The name of the network server where the object will be created. Variant (String).

but it is usually omitted. MyInt ' The following variable assignments use the Let statement. Required. You can't assign string expressions to numeric variables. and you can't assign numeric expressions to string variables. Use the IsNumeric function to determine if the Variant can be converted to a number. If you do. Remarks A value expression can be assigned to a variable or property only if it is of a data type that is compatible with the variable. Variant variables can be assigned either string or numeric expressions. follows standard variable naming conventions. Value assigned to the variable or property. Let MyStr = "Hello World" Let MyInt = 5 TypeName Returns a String that provides information about a variable. Remarks The string returned by TypeName can be any one of the following: String returned object thype Byte Integer Long Single Double Currency Decimal Date String Boolean Error Empty Null Variable An object whose type is objecttype Byte value Integer Long integer Single-precision floating-point number Double-precision floating-point number Currency value Decimal value Date value String Boolean value An error value Uninitialized No valid data 37 . an error occurs at compile time. but only a Variant whose value can be interpreted as a number can be assigned to a numeric variable. Name of the variable or property.Aaron Wirth Let varname expression Optional. Explicit use of the Let keyword is a matter of style. However. Syntax TypeName(varname) The required varname argument is a Variant containing any variable except a variable of a user-defined type. the reverse is not always true. Example: Dim MyStr. Any Variant except a Null can be assigned to a string variable. Required.

MyType = TypeName(NullVar) ' Returns "Null". MyType = TypeName(ArrayVar) ' Returns "Integer()". the returned string can be any one of the possible returned strings (or Variant) with empty parentheses appended. TypeName returns "Integer()". Syntax VarType(varname) The required varname argument is a Variant containing any variable except a variable of a user-defined type. MyType = TypeName(IntVar) ' Returns "Integer". if varname is an array of integers. Return Values Constant vbEmpty vbNull vbInteger vbLong vbSingle vbDouble vbCurrency vbDate vbString vbObject vbError vbBoolean vbVariant vbDataObject vbDecimal vbByte Value 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 17 Description Empty (uninitialized) Null (no valid data) Integer Long integer Single-precision floating-point number Double-precision floating-point number Currency value Date value String Object Error value Boolean value Variant (used only with arrays of variants) A data access object Decimal value Byte value 38 . Example: Dim MyType MyType = TypeName(StrVar) ' Returns "String". For example. MyType = TypeName(CurVar) ' Returns "Currency". VarType Returns an Integer indicating the subtype of a variable.Aaron Wirth Object Unknown Nothing An object An object whose type is unknown Object variable that doesn't refer to an object If varname is an array.

. . . Remarks The statement name determines the data type: Statement DefBool DefByte DefInt DefLng DefCur DefSng Data Type Boolean Byte Integer Long Currency Single 39 . . letterrange] . . letterrange] . and the return type for Function and Property Get procedures whose names start with the specified characters. argument. . DefCur letterrange[. Syntax DefBool letterrange[. . DefDbl letterrange[. letterrange] . or Property Get procedure name and can be any letter of the alphabet. DefDate letterrange[. . the value returned for an array of integers is calculated as vbInteger + vbArray. Example: Dim IntVar. letterrange] . . . DefDec letterrange[. . letterrange] . DefLng letterrange[. IntVar = 459: StrVar = "Hello World": DateVar = #2/12/69# MyCheck = VarType(IntVar) ' Returns 2. . The case of letters in letterrange isn't significant. . . . . letterrange] . . The names can be used anywhere in your code in place of the actual values. letterrange] . DefObj letterrange[. letterrange] . . DateVar. . . VarType (object) returns the type of the object's default property. DefVar letterrange[. DefType Used at module level to set the default data type for variables. . DefSng letterrange[. letterrange] . DefByte letterrange[. letterrange] . arguments passed to procedures. MyCheck = VarType(DateVar) ' Returns 7. DefInt letterrange[. Each argument represents the first letter of the variable.Aaron Wirth vbUserDefinedType vbArray 36 8192 Variants that contain user-defined types Array Note These constants are specified by Visual Basic for Applications. MyCheck ' Initialize variables. Function procedure. For example. StrVar. or 8194. letterrange] . letterrange] . It is always added to some other value to indicate an array of a particular type. . MyCheck = VarType(StrVar) ' Returns 8. . Remarks The VarType function never returns the value for vbArray by itself. The constant vbVariant is only returned in conjunction with vbArray to indicate that the argument to the VarType function is an array of type Variant. . The required letterrange argument has the following syntax: letter1[-letter2] The letter1 and letter2 arguments specify the name range for which you can set a default data type. DefStr letterrange[. If an object has a default property.

For example. the default data type for all variables. arguments passed to procedures. all Function procedures. and all Property Get procedures is Variant. all arguments. and the return type for Function and Property Get procedures declared in that module. 40 . a DefInt statement in one module affects only the default data type of variables. arguments. If not explicitly declared with a Deftype statement. and return types in other modules is unaffected.Aaron Wirth DefDbl DefDec DefDate DefStr DefObj DefVar Double Decimal (not currently supported) Date String Object Variant A Deftype statement affects only the module where it is used. the default data type of variables.

string expression. Date.Aaron Wirth Date/Time Date Returns a Variant (Date) containing the current system date. where mm (01-12). that can represent a time. 1980 through Dec 31. Syntax Now Example: Private Sub Form_Load() Dim s As Date s = Now Label1 = s End Sub ‘Displays the date and time in label1 Timer Timers execute code repeatedly according to the Interval you specify. For example. day and year. dd (01-30) and yyyy (1400-1523) are the Hijri month. The equivalent Gregorian range is Jan 1. 41 . Date$ returns a 10-character string of the form mm-dd-yyyy. Date$ behavior is unchanged by the Calendar property setting. If it can't be converted to a valid time. Syntax Date Remarks To set the system date. Example: Dim s as Date S = Date Label1 = s Time Sets the system time. A Timer control is not a clock and should not be relied upon to keep accurate time. but don't get in the habit of using them for everything. Set the Interval property in milliseconds. 2000 = 2 seconds. an error occurs. and if the calendar is Gregorian. If the calendar is Hijri. 2099. Syntax Time = time The required time argument is any numeric expression. Remarks If time is a string. use the Date statement. Timers are useful for checking programs conditions periodically. Example: Private Sub Form_Load() Dim s As Date s = Time Label1 = s End Sub ‘Displays the Time in label1 Now Returns a Variant (Date) specifying the current date and time according your computer's system date and time. or any combination. Time attempts to convert it to a time using the time separators you specified for your system.

number. It can be positive (to get dates in the future) or negative (to get dates in the past). To add days to date. Variant (Date) or literal representing date to which the interval is added. "31-Jan-95") In this case. If date is 31-Jan-96. 1. DateDiff Returns a Variant (Long) specifying the number of time intervals between two specified dates. or Weekday ("w").Aaron Wirth DateAdd Returns a Variant (Date) containing a date to which a specified time interval has been added. Numeric expression that is the number of intervals you want to add. you can use DateAdd to calculate a date 30 days from today or a time 45 minutes from now. firstweekofyear]]) The DateDiff function syntax has these named arguments: Part interval Description Required. date1. String expression that is the interval of time you use to calculate 42 . Syntax DateDiff(interval. date2[. Settings The interval argument has these settings: Setting yyyy q m y d w ww h n s Description Year Quarter Month Day of year Day Weekday Week Hour Minute Second Remarks You can use the DateAdd function to add or subtract a specified time interval from a date. DateAdd returns 28-Feb-95. Required. not 31-Feb-95. Required. Syntax DateAdd(interval. Example: DateAdd("m". you can use Day of Year ("y"). For example. Day ("d"). firstdayofweek[. date) The DateAdd function syntax has these named arguments: Part interval number date Description Required. String expression that is the interval of time you want to add. it returns 29-Feb-96 because 1996 is a leap year.

If not specified. Sunday (default) Monday Tuesday Wednesday Thursday Friday Saturday Description Use the NLS API setting. Two dates you want to use in the calculation. A constant that specifies the first week of the year. Variant (Date). Settings The interval argument has these settings: Setting yyyy q m y d w ww h n s Description Year Quarter Month Day of year Day Weekday Week Hour Minute Second The firstdayofweek argument has these settings: Constant vbUseSystem vbSunday vbMonday vbTuesday vbWednesday vbThursday vbFriday vbSaturday Constant vbUseSystem vbFirstJan1 vbFirstFourDays Value 0 1 2 3 4 5 6 7 Value 0 1 2 Description Use the NLS API setting.Aaron Wirth the difference between date1 and date2. date2 firstdayofweek firstweekofyear Required. A constant that specifies the first day of the week. Optional. the first week is assumed to be the week in which January 1 occurs. Start with week in which January 1 occurs (default). date1. Optional. If not specified. Sunday is assumed. Start with the first week that has at 43 .

vbFirstFullWeek 3 Start with first full week of the year. 2. DateValue Returns a Variant (Date).Aaron Wirth least four days in the new year. TheDate) MsgBox Msg ‘Displays difference between dates in number of days DateSerial Returns a Variant (Date) for a specified year. Integer. or a numeric expression. months. Remarks You can use the DateDiff function to determine how many specified time intervals exist between two dates. MyDate = DateSerial(1969. Example: Dim MyDate ' MyDate contains the date for February 12. month. you can also specify relative dates for each argument using any numeric expression that represents some number of days. day. inclusive. 1991. or years before or after a certain date. 100 through December 31. 44 . Dim Msg TheDate = InputBox("Enter a date") Msg = "Days from today: " & DateDiff("d". day) The DateSerial function syntax has these named arguments: Part year month day Description Required. 1969. and year according to the Short Date format you specified for your system. 1–31 for days and 1–12 for months. Number between 100 and 9999. 12) ' Return a date. such as December 31. Any numeric expression. or both a date and time. in that range. either in long or abbreviated form. Integer. However. Syntax DateValue(date) The required date argument is normally a string expression representing a date from January 1. month. 9999. Example: Dim TheDate As Date ' Declare variables. Required. DateValue also recognizes unambiguous dates that contain month names. Remarks If date is a string that includes only numbers separated by valid date separators. 1991. For example. Syntax DateSerial(year. Remarks To specify a date. the range of numbers for each DateSerial argument should be in the accepted range for the unit. in addition to recognizing 12/30/1991 and 12/30/91. you might use DateDiff to calculate the number of days between two dates. or the number of weeks between today and the end of the year. a time. DateValue recognizes the order for month. Any numeric expression. 1991 and Dec 30. However. Now. Integer. date can also be any expression that can represent a date. that is. DateValue also recognizes December 30. Required. For example. and day.

string expression. Null is returned. abbreviate. For example. Month Returns a Variant (Integer) specifying a whole number between 1 and 12. MyMonth = Month(MyDate) ' MyMonth contains 2. Example: Dim MyDate. firstdayofweek) The WeekdayName function syntax has these parts: 45 . Boolean value that indicates if the month name is to be abbreviated. MyYear = Year(MyDate) ' MyYear contains 1969. February is 2. 1969# ' Assign a date. Example: Dim MyDate. the default is False. The numeric designation of the month. and so on. Syntax MonthName(month[. MyMonth MyDate = #February 12.Aaron Wirth Example: Dim MyDate MyDate = DateValue("February 12. 1969# ' Assign a date. Null is returned. numeric expression. 1969") ' Returns 12/02/1965 Year Returns a Variant (Integer) containing a whole number representing the year. which means that the month name is not abbreviated. or any combination. MyYear MyDate = #February 12. abbreviate]) The MonthName function syntax has these parts: Part month abbreviate Description Required. Optional. If omitted. Syntax WeekdayName(weekday. string expression. If date contains Null. or any combination. Syntax Month(date) The required date argument is any Variant. that can represent a date. MonthName Returns a string indicating the specified month. Syntax Year(date) The required date argument is any Variant. January is 1. representing the month of the year. numeric expression. that can represent a date. inclusive. If date contains Null. Example: Private Sub Form_Load() Label1 = MonthName(11) End Sub ‘Returns November WeekDayName Returns a string indicating the specified day of the week.

which means that the weekday name is not abbreviated. firstdayofweek Settings The firstdayofweek argument can have the following values: Constant vbUseSystem vbSunday vbMonday vbTuesday vbWednesday vbThursday vbFriday vbSaturday Value 0 1 2 3 4 5 6 7 Description Use National Language Support (NLS) API setting. If date contains Null. If omitted. 46 . Null is returned. Numeric value of each day depends on setting of the firstdayofweek setting. If time contains Null. the default is False.Aaron Wirth Part weekday abbreviate Description Required. Hour Returns a Variant (Integer) specifying a whole number between 0 and 23. Example: Dim MyDate. numeric expression. string expression. Syntax Hour(time) The required time argument is any Variant. numeric expression. Syntax Day(date) The required date argument is any Variant. that can represent a date. The numeric designation for the day of the week. Sunday (default) Monday Tuesday Wednesday Thursday Friday Saturday Example: Label1 = WeekdayName(3) ‘Returns Wednesday Day Returns a Variant (Integer) specifying a whole number between 1 and 31. string expression. See Settings section for values. Boolean value that indicates if the weekday name is to be abbreviated. or any combination. or any combination. inclusive. representing the day of the month. inclusive. that can represent a time. 1969# ' Assign a date. Optional. MyDay = Day(MyDate) ' MyDay contains 12. Optional. Numeric value indicating the first day of the week. Null is returned. MyDay MyDate = #February 12. representing the hour of the day.

and second. The following example uses expressions instead of absolute time numbers.). representing the second of the minute. Minute Returns a Variant (Integer) specifying a whole number between 0 and 59. However. Variant (Integer). MySecond = Second(MyTime) ' MySecond contains 17. or any combination. MySecond MyTime = #4:35:17 PM# ' Assign a time. that is. Syntax TimeSerial(hour. string expression. or a numeric expression. If time contains Null. If time contains Null. Remarks To specify a time. that can represent a time. or any combination. MyHour = Hour(MyTime) ' MyHour contains 16.Aaron Wirth Example: Dim MyTime. Example: Dim MyTime MyTime = TimeSerial(16. string expression. Second Returns a Variant (Integer) specifying a whole number between 0 and 59. MyMinute MyTime = #4:35:17 PM# ' Assign a time.M. minute. 0–23 for hours and 0–59 for minutes and seconds. numeric expression. inclusive. Required.M. Example: Dim MyTime.) and 23 (11:00 P. or seconds before or after a certain time. second) The TimeSerial function syntax has these named arguments: Part hour minute second Description Required. you can also specify relative times for each argument using any numeric expression that represents some number of hours. numeric expression. MyMinute = Minute(MyTime) ' MyMinute contains 35. Syntax Second(time) The required time argument is any Variant. Null is returned. Null is returned. Number between 0 (12:00 A. Required. Variant (Integer). Variant (Integer). Any numeric expression. that can represent a time. 35. ' MyTime contains serial 47 . the range of numbers for each TimeSerial argument should be in the normal range for the unit. MyHour MyTime = #4:35:17 PM# ' Assign a time. representing the minute of the hour. Syntax Minute(time) The required time argument is any Variant. such as 11:59:59. Any numeric expression. TimeSerial Returns a Variant (Date) containing the time for a specific hour. inclusive. Example: Dim MyTime. minutes. inclusive. 17) ' representation of 4:35:17 PM. minute.

Optional. A constant that specifies the first day of the week. inclusive. Null is returned. Syntax TimeValue(time) The required time argument is normally a string expression representing a time from 0:00:00 (12:00:00 A.). [firstdayofweek]) The Weekday function syntax has these named arguments: Part date firstdayofweek Description Required. vbSunday is assumed. However. or any combination. Sunday (default) Monday Tuesday Wednesday Thursday Friday Saturday Return Values The Weekday function can return any of these values: Constant vbSunday Value 1 Description Sunday 48 . If time contains Null. Example: Dim MyTime MyTime = TimeValue("4:35:17 PM") ' Returns 4:35:17 PM WeekDay Returns a Variant (Integer) containing a whole number representing the day of the week. time can also be any expression that represents a time in that range. string expression. If date contains Null.M. that can represent a date. If not specified. Variant. Null is returned. Syntax Weekday(date.) to 23:59:59 (11:59:59 P.M. Settings The firstdayofweek argument has these settings: Constant vbUseSystem vbSunday vbMonday vbTuesday vbWednesday vbThursday vbFriday vbSaturday Value 0 1 2 3 4 5 6 7 Description Use the NLS API setting.Aaron Wirth TimeValue Returns a Variant (Date) containing the time. numeric expression.

MyWeekDay MyDate = #February 12. MyWeekDay = Weekday(MyDate) ' MyWeekDay contains 4 because ' MyDate represents a Wednesday. 49 .Aaron Wirth vbMonday vbTuesday vbWednesday vbThursday vbFriday vbSaturday 2 3 4 5 6 7 Monday Tuesday Wednesday Thursday Friday Saturday Example: Dim MyDate. 1969# ' Assign a date.

Display Yes and No buttons. and Ignore buttons. context must also be provided. Display Abort. and Cancel buttons. title] [. If context is provided. If prompt consists of more than one line. depending on the width of the characters used. Display OK and Cancel buttons. or carriage return – linefeed character combination (Chr(13) & Chr(10)) between each line. and returns an Integer indicating which button the user clicked. Display Retry and Cancel buttons. Optional. Optional. context]) The MsgBox function syntax has these named arguments: Part prompt Description Required. Display Information Message icon. If you omit title. Optional. buttons title helpfile context Settings The buttons argument settings are: Constant vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel vbCritical vbQuestion vbExclamation vbInformation vbDefaultButton1 vbDefaultButton2 vbDefaultButton3 Value 0 1 2 3 4 5 16 32 48 64 0 256 512 Description Display OK button only. Optional. Display Critical Message icon. If helpfile is provided. Display Warning Message icon. Syntax MsgBox(prompt[. a linefeed character (Chr(10)). you can separate the lines using a carriage return character (Chr(13)). the default value for buttons is 0. waits for the user to click a button. the icon style to use. buttons] [. Third button is default. String expression displayed in the title bar of the dialog box. Display Yes. First button is default. and the modality of the message box.Aaron Wirth Miscellaneous MsgBox Displays a message in a dialog box. Second button is default. If omitted. 50 . the identity of the default button. helpfile must also be provided. String expression displayed as the message in the dialog box. No. helpfile. Numeric expression that is the sum of values specifying the number and type of buttons to display. String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. The maximum length of prompt is approximately 1024 characters. Display Warning Query icon. Retry. the application name is placed in the title bar. Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author.

Syntax Shell(pathname[. all applications are suspended until the user responds to the message box. The windowstyle named argument has these values: Constant vbHide Value 0 Description Window is hidden and focus is passed to the hidden window. vbNormalFocus vbMinimizedFocus vbMaximizedFocus vbNormalNoFocus vbMinimizedNoFocus 1 2 3 4 6 51 . If windowstyle is omitted. Optional. The vbHide constant is not applicable on Macintosh platforms. the user must respond to the message box before continuing work in the current application. windowstyle only determines whether or not the application gets the focus when it is run. Adds Help button to the message box Specifies the message box window as the foreground window Text is right aligned Specifies text should appear as right-to-left reading on Hebrew and Arabic systems vbSystemModal vbMsgBoxHelpButton VbMsgBoxSetForeground vbMsgBoxRight vbMsgBoxRtlReading 4096 16384 65536 524288 1048576 Shell Runs an executable program and returns a Variant (Double) representing the program's task ID if successful. Variant (String). Application modal.0 or later). the program is started minimized with focus. Window is maximized with focus. Window is displayed as an icon with focus. The currently active window remains active. Window has focus and is restored to its original size and position. Variant (Integer) corresponding to the style of the window in which the program is to be run. Window is displayed as an icon.Aaron Wirth vbDefaultButton4 vbApplicationModal 768 0 Fourth button is default. The currently active window remains active. System modal. Window is restored to its most recent size and position. otherwise it returns zero. may include directory or folder and drive.windowstyle]) The Shell function syntax has these named arguments: Part pathname windowstyle Description Required. On the Macintosh (System 7. Name of the program to execute and any required arguments or command-line switches.

MyObject. it returns the task ID of the started program. 128 + I) ' Same as RGB(75. 52 . 1) ' Run Calculator. If the Shell function can't start the named program. that represents the green component of the color. 0. and blue values they include: Color Black Blue Green Cyan Red Magenta Yellow White Red Value 0 0 0 0 255 255 255 255 Green Value 0 0 255 255 0 0 255 255 Blue Value 0 255 0 255 0 255 0 255 Example: Dim RED. Remarks Application methods and properties that accept a color specification expect that specification to be a number representing an RGB color value. Number in the range 0–255. MyObject Red = RGB(255. Example: ' Specifying 1 as the second argument opens the application in ' normal size and gives it the focus. and blue to cause a specific color to be displayed. that represents the red component of the color. RGBValue.Aaron Wirth Remarks If the Shell function successfully executes the named file. 0) ' Set the Color property of ' MyObject to Red. Number in the range 0–255. green. Variant (Integer).Color = RGB(255. green. RGBValue = RGB(I. 64 + I. Variant (Integer). The task ID is a unique number that identifies the running program. blue) The RGB function syntax has these named arguments: Part red green blue Description Required. Required.EXE". that represents the blue component of the color. 0. an error occurs. Variant (Integer). 0) ' Return the value for Red. green. I = 75 ' Initialize offset. Required. The following table lists some standard colors and the red. The value for any argument to RGB that exceeds 255 is assumed to be 255. Syntax RGB(red. inclusive. Dim RetVal RetVal = Shell("C:\WINDOWS\CALC. 203). I. An RGB color value specifies the relative intensity of red. inclusive. inclusive. RGB Returns a Long whole number representing an RGB color value. Number in the range 0–255. 139.

context]) The InputBox function syntax has these named arguments: 53 . Beep ' Sound a tone.Aaron Wirth QBColor Returns a Long representing the RGB color code corresponding to the specified color number. Example: Dim I For I = 1 To 3 ' Loop 3 times. Syntax QBColor(color) The required color argument is a whole number in the range 0–15. Next I InputBox Displays a prompt in a dialog box. MyForm As Form) MyForm. and returns a String containing the contents of the text box.BackColor = QBColor(ColorCode) End Sub Beep Sounds a tone through the computer's speaker. default] [. Syntax Beep Remarks The frequency and duration of the beep depend on your hardware and system software. waits for the user to input text or click a button. Settings The color argument has these settings: Number 0 1 2 3 4 5 6 7 Color Black Blue Green Cyan Red Magenta Yellow White Number 8 9 10 11 12 13 14 15 Color Gray Light Blue Light Green Light Cyan Light Red Light Magenta Light Yellow Bright White Example: Sub ChangeBackColor (ColorCode As Integer. and vary among computers. title] [. xpos] [. helpfile. Syntax InputBox(prompt[. ypos] [.

in twips. String expression displayed in the title bar of the dialog box. 10) ' Display dialog box at position 100. Optional. depending on the width of the characters used. in twips. MyValue Message = "Enter a value between 1 and 3" ' Set prompt. Title. ' Display message. Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author. .Aaron Wirth Part prompt Description Required. The object can be manipulated programmatically in its Initialize event procedure. The Help button is added automatically. Default. Use the Show method to make the object visible. Default = "1" ' Set default. Example: Private Sub Command1_Click () Load Form2 Form2. String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. the vertical distance of the upper edge of the dialog box from the top of the screen. Optional. the text box is displayed empty. String expression displayed in the text box as the default response if no other input is provided. the application name is placed in the title bar. MyValue = InputBox(Message. Optional. MyValue = InputBox(Message. Title = "InputBox Demo" ' Set title. Syntax Load object The object placeholder represents an object expression that evaluates to an object in the Applies To list. 100) Load Loads an object but doesn't show it. Title. Title. the dialog box is vertically positioned approximately one-third of the way down the screen. String expression displayed as the message in the dialog box. . Numeric expression that specifies. If helpfile is provided. 100. a user can't interact with it. Optional. If context is provided. the dialog box is horizontally centered. or carriage return– linefeed character combination (Chr(13) & Chr(10)) between each line. but isn't visible. "DEMO. MyValue = InputBox(Message. Until an object is visible. a linefeed character (Chr(10)).HLP". Optional. If xpos is omitted. Numeric expression that specifies. Remarks When an object is loaded.Show End Sub 54 . you can separate the lines using a carriage return character (Chr(13)). 100. context must also be provided. If ypos is omitted. The maximum length of prompt is approximately 1024 characters. it is placed in memory. the horizontal distance of the left edge of the dialog box from the left edge of the screen. If you omit title. Default. . Title. Optional. Default) ' Use Helpfile and context. title default xpos ypos helpfile context Example: Dim Message. helpfile must also be provided. If prompt consists of more than one line. If you omit default. title. and default value.

use "ABC" for string. it's removed from memory and all memory associated with the object is reclaimed. To represent the letters A. percent sign (%). Boolean value specifying the wait mode. Optional. Brackets ([ ]) have no special meaning to SendKeys. but you must enclose them in braces. Until it is placed in memory again using the Load statement. Syntax SendKeys string[. brackets do have a special meaning that may be significant when dynamic data exchange (DDE) occurs. To specify a single keyboard character.Aaron Wirth UnLoad Removes an object from memory. enclose it within braces ({}). To specify characters that aren't displayed when you press a key. and the object can't be manipulated programmatically. If False (default). such as ENTER or TAB. String expression specifying the keystrokes to send. and parentheses ( ) have special meanings to SendKeys. control is returned to the procedure immediately after the keys are sent. For example. keystrokes must be processed before control is returned to the procedure.Hide Unload Form2 End Sub SendKeys Sends one or more keystrokes to the active window as if typed at the keyboard. Example: Private Sub Command2_Click() Form2. tilde (~). To specify brace characters. caret (^). use the character itself. To represent more than one character. To specify one of these characters. to represent the letter A. use the codes shown below: 55 . wait] The SendKeys statement syntax has these named arguments: Part string Wait Description Required. use {{} and {}}. For example. In other applications. Remarks Each key is represented by one or more characters. append each additional character to the one preceding it. and keys that represent actions rather than characters. to specify the plus sign. B. a user can't interact with an object. Remarks When an object is unloaded. Syntax Unload object The required object placeholder represents an object expression that evaluates to an object in the Applies To list. If True. use {+}. and C. The plus sign (+). use "A" for string.

{LEFT 42} means press the LEFT ARROW key 42 times. CTRL. To specify repeating keys. {h 10} means press H 10 times. enclose the code for those keys in parentheses. followed by C without SHIFT. use the form {key number}. precede the key code with one or more of the following codes: Key SHIFT CTRL ALT Code + ^ % To specify that any combination of SHIFT. to specify to hold down SHIFT while E and C are pressed. 56 . use "+(EC)". and ALT keys. use "+EC". or {BKSP} {BREAK} {CAPSLOCK} {DELETE} or {DEL} {DOWN} F3 {END} {ENTER}or ~ {ESC} {HELP} {HOME} {INSERT} or {INS} {LEFT} {NUMLOCK} {PGDN} {PGUP} {PRTSC} {RIGHT} F4 F5 F6 F7 F8 F9 F10 F11 F12 F13 F14 F15 F16 {F3} {F4} {F5} {F6} {F7} {F8} {F9} {F10} {F11} {F12} {F13} {F14} {F15} {F16} Key SCROLL LOCK TAB UP ARROW F1 F2 Code {SCROLLLOCK} {TAB} {UP} {F1} {F2} To specify keys combined with any combination of the SHIFT. For example. and ALT should be held down while several other keys are pressed.Aaron Wirth KeyCodes Key BACKSPACE BREAK CAPS LOCK DEL or DELETE DOWN ARROW END ENTER ESC HELP HOME INS or INSERT LEFT ARROW NUM LOCK PAGE DOWN PAGE UP PRINT SCREEN RIGHT ARROW Code {BACKSPACE}. For example. CTRL. {BS}. You must put a space between key and number. To specify to hold down SHIFT while E is pressed.

The full path to a picture file. wait] The AppActivate statement syntax has these named arguments: Part title Description Required. 57 . Example: Command1_Click () Image1. Boolean value specifying whether the calling application has the focus before activating another. The task ID returned by the Shell function can be used in place of title to activate an application. Required. the specified application is immediately activated. String expression specifying the title in the title bar of the application window you want to activate.jpg in Image1 AppActivate Activates an application window. then activates the specified application.jpg) End Sub ‘Loads the Picture Blah.Aaron Wirth Example: Command1_Click () Text1. Syntax object.SetFocus SendKeys “{Backspace}” End Sub ‘Deletes last character in Text1 Command1_Click () SendKeys "%{F4}" End Sub ‘Closes current window/program LoadPicture Specifies the bitmap to display on an object. Syntax AppActivate title[. If True. the calling application waits until it has the focus. Use the Shell function to start an application and set the window style.Picture = LoadPicture(C:\Blah. A valid object. Example: Command1_Click () AppActivate "Microsoft Word" End Sub ' Activates Microsoft Word. If False (default). Focus moves from the activated application window when the user takes some action to change the focus or close the window. even if the calling application does not have the focus. wait Remarks The AppActivate statement changes the focus to the named application or window but does not affect whether it is maximized or minimized. Optional.Picture = LoadPicture( pathname ) The Picture property syntax has these parts: Part object pathname Description Required.

otherwise. MyVar = "45 Help" ' Assign value. IsEmpty only returns meaningful information for variants. IsNumeric returns False if expression is a date expression. MyCheck = IsEmpty(MyVar) ' Returns False. IsNumeric Returns a Boolean value indicating whether an expression can be evaluated as a number. because IsEmpty is used to determine if individual variables are initialized. IsNull returns False. If expression consists of more than one variable. Remarks IsNull returns True if expression is Null. Remarks IsNumeric returns True if the entire expression is recognized as a number. 58 . MyCheck = IsEmpty(MyVar) ' Returns True. Example: MyVar = Null ' Assign Null. the expression argument is most often a single variable name.95" ' Assign value. it returns False. Syntax IsNumeric(expression) The required expression argument is a Variant containing a numeric expression or string expression. Remarks IsEmpty returns True if the variable is uninitialized. otherwise. MyVar = Empty ' Assign Empty. MyCheck = IsNumeric(MyVar) ' Returns True. Null in any constituent variable causes True to be returned for the entire expression Example: MyVar = "" MyCheck = IsNull(MyVar) MyVar = Null MyCheck = IsNull(MyVar) ' Returns False. it returns False. False is always returned if expression contains more than one variable. MyCheck = IsNumeric(MyVar) ' Returns False.Aaron Wirth Values IsNull Returns a Boolean value that indicates whether an expression contains no valid data (Null). ' Returns True. Syntax IsEmpty(expression) The required expression argument is a Variant containing a numeric or string expression. otherwise. IsEmpty Returns a Boolean value indicating whether a variable has been initialized. Syntax IsNull(expression) The required expression argument is a Variant containing a numeric expression or string expression. However. Example: MyVar = "459. or is explicitly set to Empty.

. MyString Number = 53 ' Initialize variable.. Optional.Else Statement Conditionally executes a group of statements. One or more statements executed if no previous condition or condition-n expression is True. Optional. condition is treated as False.. The expression is True if objectname is of the object type specified by objecttype. Syntax End End Function End If End Property End Select End Sub 59 . If Number < 10 Then Digits = 1 ElseIf Number < 100 Then ' Condition evaluates to True so the next statement is executed. One or more statements separated by colons. One or more statements executed if associated condition-n is True. depending on the value of an expression. The objectname is any object reference and objecttype is any valid object type.Then..Then. Digits... [Else [elsestatements]] End If The If. Digits = 2 Else Digits = 3 End If End Statements Ends a procedure or block.Aaron Wirth Loops and Conditional If. Example: Dim Number. executed if condition is True.. Optional. Syntax If condition Then [statements] [Else elsestatements] Or.. statements condition-n elseifstatements elsestatements Optional in block form. Same as condition..Else statement syntax has these parts: Part condition Description Required. otherwise it is False. required in single-line form that has no Else clause. you can use the block form syntax: If condition Then [statements] [ElseIf condition-n Then [elseifstatements] .. One or more of the following two types of expressions: A numeric expression or string expression that evaluates to True or False. If condition is Null. An expression of the form TypeOf objectname Is objecttype.

Property Get. The Stop statement suspends execution. Example: If Label1 = “Blah” then Stop End if 60 . it doesn't close any files or clear variables. End Function End If End Property End Select End Sub End Type End With Remarks When executed. use the Stop statement instead. Required to end a Property Let.Aaron Wirth End Type End With The End statement syntax has these forms: Statement End Description Terminates execution immediately. You can then resume execution while preserving the value of those variables. unless it is in a compiled executable (. Never required by itself but may be placed anywhere in a procedure to end code execution. Required to end a user-defined type definition (Type statement). Required to end a Sub statement. close files opened with the Open statement and to clear variables. but unlike End.exe) file. the End statement resets all module-level variables and all static local variables in all modules. Pword PassWord = "Swordfish" Pword = InputBox("Type in your password") If Pword <> PassWord Then MsgBox "Sorry. Required to end a Function statement. Syntax Stop Remarks You can place Stop statements anywhere in procedures to suspend execution. incorrect password" End End If End Sub Stop Suspends execution. Required to end a block If…Then…Else statement. Required to end a With statement. or Property Set procedure. Example: Sub Form_Load Dim Password. To preserve the value of these variables. Using the Stop statement is similar to setting a breahkpoint in the code. Required to end a Select Case statement.

expr-n. Use structured control statements (Do.Loop. Goto Branches unconditionally to a specified line within a procedure. Syntax Switch(expr-1.Aaron Wirth Switch Evaluates a list of expressions and returns a Variant value or an expression associated with the first expression in the list that is True. Note Too many GoTo statements can make code difficult to read and debug.. value-2 … [.. "French") End Function ‘This example uses the Switch function to return the name of a language that matches the name of a city. Remarks GoTo can branch only to lines within the procedure where it appears. Select Case) whenever possible.Else. Value or expression to be returned if the corresponding expression is True. and so on.Next. Switch returns value-1. Required... Switch returns a Null value if:  None of the expressions is True. "Italian". Syntax GoTo line The required line argument can be any line label or line number. if expr-1 is True. Example: Function MatchUp (CityName As String) Matchup = Switch(CityName = "London"..Then. If the parts aren't properly paired.. For example. If. Example: If Label1 = “Blah” then Goto Something Else End Something: End if 61 . Remarks The Switch function argument list consists of pairs of expressions and values. CityName = "Paris".value-n]]) The Switch function syntax has these parts: Part expr value Description Required. expr-2. CityName _ = "Rome". "English". but expr-2 is True.  The first True expression has a corresponding value that is Null. The expressions are evaluated from left to right. and the value associated with the first expression to evaluate to True is returned. value-1[. Variant expression you want to evaluate. a run-time error occurs.. If expr-1 is False.. Switch returns value-2. For.

Syntax GoSub line . Control drops to the statement following On. You can mix line numbers and line labels in the same list.. If expression is any number other than a whole number. Remarks You can use GoSub and Return anywhere in a procedure.Aaron Wirth On. Note You can't enter or exit Sub procedures with GoSub.... but GoSub and the corresponding Return statement must be in the same procedure... if you use more labels or numbers than fit on a single line..GoSub.GoTo.... List of line numbers or line labels separated by commas..GoSub or On.. A subroutine can contain more than one Return statement. it is rounded before it is evaluated. line .GoSub or On. destinationlist Remarks The value of expression determines which line is branched to in destinationlist..Return Statement Branches to and returns from a subroutine within a procedure.GoTo Statements Branch to one of several specified lines.GoTo. An error occurs. inclusive.GoSub and On.. If the value of expression is less than 1 or greater than the number of items in the list. you must use the line-continuation character to continue the logical line onto the next physical line.... GoSub. An error occurs.....GoTo. You can use as many line labels and line numbers as you like with On. On.. Syntax On expression GoSub destinationlist On expression GoTo destinationlist The On..GoTo statement syntax has these parts: Part expression Description Required.Return... depending on the value of an expression..GoSub and On. Return The line argument can be any line label or line number. 62 . 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. However. Required.. Any numeric expression that evaluates to a whole number between 0 and 255.. one of the following results occurs: If expression is Equal to 0 Greater than number of items in list Negative Greater than 255 Then Control drops to the statement following On.

63 .Aaron Wirth Example: Sub GosubDemo() Dim Num ' Solicit a number from the user.Width = 2000 .. If Num > 0 Then GoSub MyRoutine Debug. Required.") ' Only use routine if user enters a positive number.Height = 2000 . Numeric variable used as a loop counter. Example: With MyLabel .Caption = "This is MyLabel" End With For. Num = InputBox("Enter a positive number to be divided by 2. MyRoutine: Num = Num/2 ' Perform the division. End Sub ' following the GoSub statement. The following example illustrates use of the With statement to assign values to several properties of the same object. to change a number of different properties on a single object. Name of an object or a user-defined type.Next Statement Repeats a group of statements a specified number of times. For example. Syntax With object [statements] End With The With statement syntax has these parts: Part object statements Description Required. The variable can't be a Boolean or an array element. place the property assignment statements within the With control structure. referring to the object once instead of referring to it with each property assignment. One or more statements to be executed on object. Syntax For counter = start To end [Step step] [statements] [Exit For] [statements] Next [counter] The For…Next statement syntax has these parts: Part counter start Description Required.Print Num Exit Sub ' Use Exit to prevent an error. Optional. Return ' Return control to statement. With Statement Executes a series of statements on a single object or a user-defined type. Remarks The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. Initial value of counter..

. condition is treated as False. Counter = Counter + 1 ' Increment Counter. Amount counter is changed each time through the loop.. Optional.Wend loops can be nested to any level. If condition is Null. At this point. If it is not True.. Control then returns to the While statement and condition is again checked.Print Counter ' Prints 20 in the Immediate window. execution resumes with the statement following the Wend statement.. Example: Dim Counter Counter = 0 ' Initialize variable. Final value of counter. Next Chars ' Increment counter MyString = MyString & " " ' Append a space. Each Wend matches the most recent While.Aaron Wirth end step statements Required. For Chars = 0 To 9 ' Set up 10 repetitions. Remarks If condition is True.. Optional.Wend Statement Executes a series of statements as long as a given condition is True. While. MyString = MyString & Chars ' Append number to string..Loop statement provides a more structured and flexible way to perform looping. all statements are executed until the Wend statement is encountered. If condition is still True. MyString For Words = 10 To 1 Step -1 ' Set up 10 repetitions. Debug. Wend ' End While loop when Counter > 19. Syntax While condition [statements] Wend The While. Numeric expression or string expression that evaluates to True or False. either the statements in the loop execute again (based on the same test that caused the loop to execute initially). One or more statements executed while condition is True.Wend statement syntax has these parts: Part condition statements Description Required. or the loop is exited and execution continues with the statement following the Next statement. One or more statements between For and Next that are executed the specified number of times. 64 . step defaults to one.. While Counter < 20 ' Test value of Counter. If not specified. The value of the step argument determines loop processing as follows: Value Positive or 0 Negative Loop executes if counter <= end counter >= end After all statements in the loop have executed. the process is repeated.. Remarks The step argument can be either positive or negative. Chars. Optional. Tip The Do. Next Words While. step is added to counter. Example: Dim Words.

One or more statements that are repeated while.Aaron Wirth Do. Check = False ' Set value of flag to False. Syntax Do [{While | Until} condition] [statements] [Exit Do] [statements] Loop Or. you can use this syntax: Do [statements] [Exit Do] [statements] Loop [{While | Until} condition] The Do Loop statement syntax has these parts: Part condition statements Description Optional. When used within nested Do…Loop statements. condition is treated as False. Required. Value or expression returned if expr is False. truepart. If Counter = 10 Then ' If condition is True. in which case the Exit Do statement transfers control to the statement immediately following the Loop. falsepart) The IIf function syntax has these named arguments: Part expr truepart falsepart Description Required. Exit Do is often used after evaluating some condition. Example: Dim Check. Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs.. If condition is Null. Syntax IIf(expr. 65 . Counter Check = True: Counter = 0 ' Initialize variables. End If Loop Loop Until Check = False ' Exit outer loop immediately. or until.Loop Statement Repeats a block of statements while a condition is True or until a condition becomes True. Counter = Counter + 1 ' Increment Counter.. Do ' Outer loop. If…Then. condition is True. for example. Remarks Any number of Exit Do statements may be placed anywhere in the Do…Loop as an alternate way to exit a Do…Loop. Exit Do ' Exit inner loop. IIF Returns one of two parts. Numeric expression or string expression that is True or False. Value or expression returned if expr is True. Required. depending on the evaluation of an expression. Expression you want to evaluate. Do While Counter < 20 ' Inner loop.

. the statements in the loop continue to execute for each element. or any specific object variable. Exit For ' Exit loop. Example: Dim Found. MyCollection Found = False ' Initialize variable.Each block is entered if there is at least one element in group.. Optional. If there are more elements in group. Required.Text = "Hello" Then ' If Text equals "Hello".. Name of an object collection or array (except an array of userdefined types). if evaluating falsepart results in a division by zero error.. Variable used to iterate through the elements of the collection or array.. an error occurs even if expr is True. For Each MyObject In MyCollection ' Iterate through each element. For example. the loop is exited and execution continues with the statement following the Next statement. MyObject. Exit For is often used after evaluating some condition. Example: Function CheckIt (TestMe As Integer) CheckIt = IIf(TestMe > 1000. "Small") End Function For Each.Each. "Large". you should watch for undesirable side effects. even though it returns only one of them..Aaron Wirth Remarks IIf always evaluates both truepart and falsepart. and transfers control to the statement immediately following Next.Next Statement Repeats a group of statements for each element in an array or collection. When there are no more elements in group. for example If…Then. Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. If MyObject. a generic object variable. element can only be a Variant variable. all the statements in the loop are executed for the first element in group. element can only be a Variant variable. End If Next 66 .. For arrays. Once the loop has been entered. One or more statements that are executed on each item in group. Found = True ' Set Found to True. Because of this.Next statement syntax has these parts: Part element Description Required. Syntax For Each element In group [statements] [Exit For] [statements] Next [element] The For. group statements Remarks The For. For collections..

One or more statements executed if testexpression matches any part of expressionlist-n. If not supplied. Example: Dim Number Number = 8 ' Initialize variable.Print "Not between 1 and 10" End Select 67 . Required if a Case appears. If testexpression matches an expressionlist expression in more than one Case clause. the statements following that Case clause are executed up to the next Case clause. Debug. If you use the To keyword. The Case Else clause is used to indicate the elsestatements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. Optional. Case 1 To 5 ' Number between 1 and 5. the smaller value must appear before To. depending on the value of an expression. Select Case Number ' Evaluate Number. Syntax Select Case testexpression [Case expressionlist-n [statements-n]] . One or more statements executed if testexpression doesn't match any of the Case clause. Debug. Optional. expression To expression... the Is keyword is automatically inserted. 7.Print "Between 6 and 8" Case 9 To 10 ' Number is 9 or 10. The To keyword specifies a range of values. Is comparisonoperator expression. Although not required. statements-n elsestatements Remarks If testexpression matches any Case expressionlist expression. up to End Select. Case 6. only the statements following the first match are executed. Debug. 8 ' Number between 6 and 8. or.Aaron Wirth Select Case Statement Executes one of several groups of statements. If no Case expressionlist matches testexpression and there is no Case Else statement. Use the Is keyword with comparison operators (except Is and Like) to specify a range of values.Print "Between 1 and 5" ' The following is the only Case clause that evaluates to True. Control then passes to the statement following End Select. [Case Else [elsestatements]] End Select The Select Case statement syntax has these parts: Part testexpression expressionlist-n Description Required. execution continues at the statement following End Select. it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values. Any numeric expression or string expression. Delimited list of one or more of the following forms: expression. Debug. for the last clause.Print "Greater than 8" Case Else ' Other values. inclusive.

Sign up to vote on this title
UsefulNot useful