Document Keys
Listed below are various conventions used by this document and which are typical of most computer documents. The syntax for the commands is copied straight from the Microsoft on-line help subsystem that is available by selecting a command in the VB editor and pressing the F1 key.
- Bolded items in Commands are Visual Basic keywords, which are recognized as reserved commands, functions or pieces thereof.
- Italicized items are user-defined names or processes (statements, expressions, etc.)
- Items in [Square Brackets] are optional in the syntax definition.
- Items in {Braces} are required, but you must only select one of a choice.
- A vertical bar ( | ) indicates a choice of any one of these items.
- Ellipses (...) indicate that the item can be repeated as often as needed. This is usually preceded with a comma (,) somewhere in the definition.
Data Types
Data types are different ways of storing computer information, generally used to speed up computer calculations.
Data Type index:
Short,Integer,Long
String,Char
Object/Variant
Single,Double
Decimal
Boolean
Byte
Date
Currency
User-Defined
- ⮤ Integer, Long (long integer), Short
- Any number without decimal points, such as 0, 1, 77, 1776, -10. The difference between integer and long and short is the amount of precision available for the number with Long allowing more digits (64-binary-digits) and Short allowing fewer (16-binary-digits). In older BASIC code, you may see a "%" suffix to indicate an integer variable, such as MyVar%.
- ⮤ String, Char
- Any grouping of characters (or a single character for char) available from the standard ASCII character set, which includes letters (upper and lower case), digits, punctuation, spaces, and various non-printable characters formerly used to control printer functions. A string with no characters is often miscalled "null", but should properly be called either an empty string or a string of zero length. In older BASIC code, you may see a "$" suffix to indicate a string variable, such as MyVar$.
- ⮤ Object (formerly Variant)
- Any type of data; it tries to convert data as appropriate (treat number as strings of digits, words as strings of characters, and date strings as dates.) These are less efficient than the other types, but are more flexible. These can be any object created from any Class. To be used properly, they should be converted into the proper type.
- ⮤ Single (single precision floating-point), Double (double-precision floating-point)
- Any number with decimal points, such as 3.14159, -2.0, 0.0001. The difference between single and double is the amount of precision available for the number. For example, Single could not hold all of the digits of the U.S. National Debt, but could hold a value that approximately represents it (using scientific notation.) In older BASIC code, you may see an "!" suffix to indicate a single-precision variable and a "#" suffix to indicate a double-precision variable, such as MyVar! or MyVar#.
- ⮤ Decimal
- A 16-bit integer that looks and acts like a Single/Double, but has a fixed number of decimal positions. This is a superset of the Currency data type.
- ⮤ Boolean
- Data that only allows two states, typically represented by 1 and 0 (sometimes -1 and 0), true and false, yes and no, or on and off.
- ⮤ Byte (character)
- Any single ASCII character, such as A, @, 7, {, or the Backspace key. This is closely tied to the Char data type
- ⮤ Date
- Any string appearing in the form of a valid date, such as 12/31/2000.
- ⮤ Currency
- An integer with the decimal shifted two places to the left, such as 299.95.
- ⮤ User-Defined
- Anything that you want to create yourself, such as some sort of database record.
Operators
Operators are used to tie together multiple constants (numbers, words, etc) or variables (placeholders for numbers, words, etc.) that form expressions. These expressions can be used to formulate calculations or for doing comparisons.
Operator index:
+,-
*,/,\
&,+
=,<>
<,<=,>,>=
Not
Or,And,OrElse,AndAlso
- ⮤ + (addition), - (subtraction)
- Adds, Subtracts two numbers or the values of two variables, such as 1+3, WaistSize-5.75
- ⮤ * (multiplication), / (division), \ (integer division)
- Multiplies, Divides, Integer-Divides two numbers or the values of two variables, such as 3*7, Degrees/100
- ⮤ & (new string concatenation), + (old string concatenation)
- Concatenates two strings together (and may auto-convert values that are not strings), such as "My age is " & MyAgeVariable. To avoid confusion with calculations, the "&" variation is the preferred operator for concatenation. For example, if A and B both contain numbers, does A + B mean add the values of A and B together, or concatenate them? If both variables are numeric, they will be added; if either is string, they will be concatenated; if both are variants, the results are not necessarily predictable.
- ⮤ = (equal), <> (not equal)
- Compares two things to see if they are Equal, Not Equal and returns a boolean (true/false) result. Note that "=" is also used for assignments of values to variables; to avoid this confusion, other languages will typically use == to check for equality. This will not work in VB.
- ⮤ < (less than), <= (less than or equal to), > (greater than), >= (greater than or equal to)
- Compares two things to see if the first is Less Than, Less Or Equal To, Greater Than, or Great Or Equal To the second thing and returns a boolean (true/false) result. If strings are compared, the comparison is based on the ASCII codes that correspond to each character. I.E. "A" < "B", and "Z" > "@".
- ⮤ Not
- Reverses a boolean (true/false) condition, such as Not A=B that is the same as A<>B
- ⮤ Or, And, OrElse, AndAlso
- Creates a "logical" comparison of two boolean (true/false) conditions, such as A=B And A=C, which is the same as Not(A<>B Or A<>C). ElseOr and AndAlso will only check subsequent conditions if needed.
Commands
VB Commands to define structure or process code.
Command index:
Sub
Function
Property
Rem
Call
Dim
Const
Enum
Type
Let
If-Then
Select-Case
For-Next
Do-Loop
While-Wend
On-Error
Try-Catch
Print
Debug
With
- ⮤ Sub - Starts a user-defined or system-created Subroutine definition.
- [Private | Public | Friend | Protected] [Static] Sub name [Handles objectname.eventname] ([arglist])
[statements]
[Exit Sub]
[statements]
End Sub
Typical Example:
Sub MySubroutine (Parameter1 as Variant)
' This is a subroutine that I created
End Sub - ⮤ Function - Starts a user-defined Function definition.
- [Public | Private | Friend | Protected] [Static] Function name ([arglist]) [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function
Typical Example:
Function FindAge(YearBorn As Date) As Integer
' This is a function used to calculate someone's age today
FindAge = Date() - YearBorn
End Function - ⮤ Property - Starts a user-defined property definition.
- [Public | Private | Friend] [Static] Property name ([arglist]) [As type]
Get
[statements]
End Get
Set (Value As type)
[statements]
End Set
End Property
Typical Example:
Property NewNumber() As Integer
Get
Return iSomeNumber
End Get
Set (Value As Integer)
iSomeNumber = Value
End Set
End Property - ⮤ Rem or ' - Starts a remark or comment message ignored by the computer at run-time.
- {Rem | '} comment
Typical Example:
' This is a remark that the computer will ignore when running the program - ⮤ Call - Calls a subroutine.
- [Call] name [(argumentlist)]
Typical Example:
FindAge 12/31/50 ' Notice that optional word "Call" is omitted. - ⮤ Dim - Defines a variable, including arrays with dimensions and single variables without dimensions
- Dim [WithEvents] varname[([subscripts])] [As [New] type[=InitialValue] ] [, [WithEvents] varname[([subscripts])] [As [New] type[=InitialValue] ]] . . .
Note: outside of procedures, replace Dim with a scope identier: Public, Private or Friend
Typical Example:
Dim MyAge As Integer, MyArray(50) As String - ⮤ Const - Creates a constant "variable" (i.e. the value can never be changed by the program.)
- [Public | Private] Const constname [As type] = expression
Typical Example:
Const Pi = 3.14159 - ⮤ Enum - Creates an enumerated list of constans, grouped together by a single name.
- [Public | Private] Enum enumname
enumitemname1 [=value]
[enumitemname2 [=value]...]
End Enum
Typical Example:
Private Enum GenderConstance
Female = 1
Male = 2
End Enum - ⮤ Type - Creates a user-defined object type
- [Public | Private] Type typename
Structuretype [As datatype]
End Type
Typical Example:
Type MyRecord
PersonName As String
As As Integer
End Type - ⮤ Let - Assigns a value into a variable or object property.
- [Let] varname = expression
Typical Example:
MyAge = Date - Date("12/31/50") ' Notice that the optional word "Let" is omitted and is no longer used by VB.Net. - ⮤ If-Then-Else - Creates a conditional branch within the program.
- The 'if' statement supports two formats: single-line and multi-line:
If condition Then [statements] [Else elsestatements]
If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements] ...]
[Else
[elsestatements]]
End If
Typical Examples:
If MyName = "Joe" Then Messagebox.Show "Eat at Joe's" Else Messagebox.Show "Don't eat!"
If MyName = "Joe" Then
Messagebox.Show "Eat at Joe's"
ElseIf MyName = "Mom" Then
Messagebox.Show "Eat at home"
Else
Messagebox.Show "Don't eat"
End If - ⮤ Case - Selects a process based on a structured condition.
- Select Case testexpression
[Case expressionlist-n
[statements-n]] ...
[Case Else
[elsestatements]]
End Select
Typical Example:
Select Case MyName
Case "Joe"
Messagebox.Show "Eat at Joe's"
Case "Mom"
Messagebox.Show "Eat at home"
Case Else
Messagebox.Show "Don't eat"
End Select - ⮤ For-Next - Creates an iterative (counting) loop.
- For counter = start To end [Step increment]
statements
[Exit For]
[statements]
Next [counter]
Typical Example:
Dim CounterAs Integer
Dim Sum As Integer
Sum = 0
For Counter = 0 To 100 Step 5
Sum = Sum + Counter
Next - ⮤ Do-Loop - Creates a conditional loop.
- The Do-loop has two variations: one with the condition before processing, the other after processing.
Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
Typical Example:
Do While Today = "Saturday"
Call SleepSomeMore
Today = GetDayOfWeek()
Loop
Do
PartyTillYouDrop
Loop Until Timer > TimeForWork() - ⮤ While-Wend - Creates a more simplified variation of the Do-While loop.
- While condition
[statements]
Wend
Typical Example:
While Today = "Saturday"
Call SleepSomeMore
Today = GetDayOfWeek()
Wend - ⮤ On Error-Resume - Traps application errors. (Deprecated for DotNet; see Try/Catch)
Error trapping lets you handle system-generated errors in your own code instead of letting Windows handle them. Error trapping consists of two parts: trapping the error and redirecting your code to a routine to handle this error; and resuming processing after you've handled the error. Since errors can occur almost anywhere, including sources outside of your control, error trapping should really be placed into every major routine and most minor routines (if not every routine.)
The error trapping and redirecting has three variations: redirect to a line number or reference line (GoTo), ignore the error and continue with the next line of code (Resume Next), and disable error trapping (GoTo 0)
On Error GoTo line
On Error Resume Next
On Error GoTo 0
The error processing also has three variations: Resume with the same line that caused the error and try again (0), resume with the line immediately following where the error occurred, and resume on a specified line number or reference line.
Resume [0]
Resume Next
Resume line
Typical Example:
Sub MyProc()
On Error GoTo MyProcErr
MyErr = 100 / 0 ' Division by zero causes a calculation error
Exit Sub
MyProcErr:
If Err.Number = DivByZero Then
MyErr = -1 ' Redefine the variable with a predetermined value
Resume Next' Error was handled and fixed
End If
End Sub- ⮤ Try/Catch/[Finally]
When an error may occur in a block of code, you can surround the block with a try/Catch. If the block succeeds without errors, it skips the catch block; if an error occurs during execution of the code, execution is immediately transferred to the Catch block to continue processing and will not return to the Try. If you need to process something whether an error occurs or not, such as when processing a file and anting to close the file when done, you can add a Finally block. Also note that you can catch multiple errors but the last catch should be the generic catch for "Exception." Also note that you will often want to "throw" an error up to the calling routinem in which case the finally block will run, then the calling routine will receive the error that you throw.
Syntax:
Try
StatementsToTryToProcess
Catch var As exceptiontype
StatementsIfErrorOccurs
[Throw exceptiontype]
[Finally
StatementsToRunEitherWay]
End Try
Typical Example:
Sub MyProc()
Try
MyErr = 100 / 0 ' division by zero causes a calculation error
Catch exc As Exception
If Err.Number = DivByZero Then
MyErr = -1 ' Redefine the variable with a predetermined value
End If
End Try
End Sub- ⮤ Print - Puts text onto an object that is allowed to receive it.
- The Print command formerly was used to place text onto the DOS console. In Windows, there is no DOS console, so the Print command is applied as a method associated with certain objects such as the form's background, a picture box's background, or the debug window. However, still works in the Immediate Window (Ctrl+G)
[object.]Print [[{expression | tab(expression) | spc(expression)}] [{; | ,} [{expression-n | tab(expression) | spc(expression)}]...]]
Typical Example:
MyPicture.Print "I put text on my picture box."; ' The semicolon (;) will place subsequent text on the same line
MyPicture.Print "I put more text on the same line." ' No semicolon means subsequent text is on the next line
MyPicture.Print "This appears on the next line." - ⮤ Debug.Write | Debug.WriteLine - Puts text onto an object that is allowed to receive it. The Debug.Write command is used to place text onto the output console.
- Debug.Write(expression)
Typical Example:
Debug.Write("I put text on my picture box.") - ⮤ With - Groups object variable assignments together.
- With object
[statements]
End With
Typical Example:
With MyPictureBox
.Left = 0
.Top = 0
.Visible = True
End With
Functions
Functions are routines that return a single value. The common mathematical functions, such as Square Root (Sqr), Absolute value (Abs), and Sine/Cosine/Tangent (Sin, Cos, Tan) as well as computer-specific numeric and string functions.Common global objects used as functions include Convert, Math, and MessageBox
Function index:
Int
Mod
Sgn
Msgbox
Messagebox
Str
Val
Left
Right
Mid
Substring
Instr
IndexOf
- ⮤ Int - Returns only the integer portion of a calculation, without any decimal portion.
- Int(numericexpression)
Typical Example:
intCalc = Int(100 / 3) ' result is 33 - ⮤ Mod - Returns the remainder of a division calculation.
- numericexpression Mod numericexpression
Typical Example:
Ans = 100 Mod 3 ' Returns 1 since 100/3 = 33 with 1 left over - ⮤ Sgn - Returns the mathematical sign of an expression, positive (1), negative (-1), or none (0).
- Sgn(numericexpression)
Typical Example:
Ans = Sgn(MyAge - 50) - ⮤ Msgbox - Displays a windows dialog box and awaits user response.
- [varname =] Msgbox(prompt[, buttons] [, title] [, helpfile, context])
Typical Example:
Ans = Msgbox("Are you sure you want to quit?", vbYesNo) - ⮤ Messagebox.Show() - Displays a windows dialog box and awaits user response. (Updated for VB.Net from MsgBox)
- [varname =] Messagebox.Show(prompt[, buttons] [, title] [, helpfile, context])
Typical Example:
Ans = Messagebox.Show("Are you sure you want to quit?", vbYesNo) - ⮤ Str - Converts a numeric value into a string.
- Str[$](numericexpression)
Typical Example:
strMyAge = Str(intMyAge) - ⮤ Val - Converts a string value into a number.
- Val(stringexpression)
Typical Example:
intMyAge = Val(strMyAge) - ⮤ Left - Extracts a substring from the left portion of a string. Deprecated; use Substring
- Left[$](stringexpression, length)
Typical Example:
strMonth = Left(strDate, 2) - ⮤ Right - Extracts a substring from the right portion of a string. Deprecated; use Substring
- Right[$](stringexpression, length)
Typical Example:
strYear = Right(strDate, 4) - ⮤ Mid - Extracts a substring from the middle portion of a string. Deprecated; use Substring
- Mid[$](stringexpression, startingposition[, length])
Typical Example:
strDay = Mid(strDate, 4, 2) - ⮤ Substring - Extracts a substring from a portion of a string. (Formerly Left, Mid, Right)
- One variation is as follows:
object.Substring(stringexpression, startposition, length)
Typical Example:
strMonth = txtMonth.Text.Substring(strDate, 1, 2) - ⮤ Instr - Checks for a string within a string.
- Instr([startingposition,] stringexpression, substringexpression[, comparecode])
Typical Example:
If Instr(1, strDate, "Aug", vbTextCompare) Then
Msgbox "This date is in August."
End If - ⮤ IndexOf - Checks for a string within a string. (Formerly InStr)
- object.IndexOf(stringexpression)
Typical Example:
If strDate.IndexOf("Aug") > 0 Then
Messagebox.Show("This date is in August.")
End If