Visual Basic/VB6 Command Reference

From Wikibooks, open books for an open world
Jump to: navigation, search

This page aims to be a comprehensive command reference to the MS Visual Basic 6 programming language.

String Manipulation[edit]

Asc[edit]

Returns the number corresponding to the ASCII code for the first character of string

Usage

Asc(string)

string = string containing character as first letter whose ASCII code is to be found.

Example

code = Asc("Apple")

Here code will get value 65

Chr[edit]

Returns a string character that corresponds to the ASCII code in the range 0-255. Reverse of the Asc function.

Usage

Chr(code)

code = ASCII code.

Example

char = Chr(97)

Here char gets value "a".

Len[edit]

Returns the length of a given string or 0 for Empty.

Usage

Len(expression)

expression = a string or Empty

Example

mystring = InputBox("Enter a string to test")
length = Len(mystring)
MsgBox "Length of the string is " & length

e.g. where mystring is "Hello", length will be 5.

Left[edit]

Returns a given number of characters from the left hand side of a string

Usage

Left(string,x)

string = string to use
x = number of characters

Example

mystring = InputBox("Enter a string")
mystring = Left(mystring, 4)
MsgBox "First four characters of your input are " + mystring

e.g. where the input mystring is "Hello", the output mystring will be "Hell"

Right[edit]

Returns a given number of characters from the right hand side of a string

Usage

Right(string, x)

string = string to use
x = number of characters

Example

mystring = InputBox("Enter a string")
mystring = Right(mystring, 4)
MsgBox "Last four characters of your input are " + mystring

e.g. where the input mystring is "Hello", the output mystring will be "ello"

Mid (Function)[edit]

Returns a given number of characters from the middle of a string

Usage

Mid(string, start, length)

string = string to use
start = character to start at (1 is the first character)
length = number of characters

Example

mystring = InputBox("Enter a string")
mystring = Mid(mystring, 2, 3)
MsgBox "The second, third, and fourth characters of your input are " & mystring

e.g. where the input mystring is "Hello", the output mystring will be "ell"

Mid (Statement)[edit]

Sets a given number of characters in the middle of a string equal to the same number of characters from the beginning of another string

Usage

Mid(mystring, start, length)

mystring = the string to take characters from start = character to start at (1 is the first character)
length = number of characters

Example

mystring = InputBox("Enter a string")
Mid(mystring, 2, 3) = "abcd"
MsgBox "Your string with abc as the second, third, and fourth characters of your input are " + mystring

e.g. where the input mystring is "Hello", the output mystring will be "Habco"

Trim[edit]

Removes leading and trailing spaces from a string

Usage

Trim(string)

string = string to use

Example

mystring = Trim(mystring)

e.g. where the original value of mystring was " Hello ", the new value of mystring will be "Hello".

LCase[edit]

Converts a string to lowercase

Usage

LCase(string)

string = string to use

Example

mystring = LCase(mystring)

e.g. where the original value of mystring was "HELLO", the new value of mystring will be "hello".

UCase[edit]

Converts a string to uppercase

Usage

UCase(string)

string = string to use OR character

Example

mystring = UCase(mystring)

e.g. where the original value of mystring was "Hello", the new value of mystring will be "HELLO".

String[edit]

Creates a string with the specified length of the specified character

Usage

String(length, character)

length = length of string
character = character to fill string with

Example

mystring = String(5,"a")

e.g. the new value of mystring will be "aaaaa".

Space[edit]

Creates a string with the specified length of space

Usage

Space(length)

length = length of string

Example

mystring = Space(5)

e.g. the new value of mystring will be "     ".

StrConv[edit]

Returns a converted string as specified.

Usage

StrConv(string, conversion,LCID)

string = string to use
conversion = case to convert the sting to (lowercase: vbLowerCase, uppercase: vbUpperCase, proper case (first letter in caps): vbProperCase) LCID = optional. The LocaleID, if different than the system LocaleID.

Example

mystring = StrConv(mystring, vbProperCase)

e.g. where the original value of mystring was "HELLO", the new value of mystring will be "Hello".

Mathematical Functions[edit]

Abs[edit]

Returns the absolute value of a number

Usage

Abs(number)

Example

msgbox "The absolute value of -4 is " & abs(-4)

Important note!

The Abs function only accepts numbers. Non-numeric values generate an error.

Cos[edit]

Returns the cosine of a number

Usage

Cos(integer)

Example

msgbox "The cosine of 4 is " & cos(4)

Important note!

The input angle for all VB trigometric functions should be in radians. To convert degrees to radians, multiply degrees by pi / 180.

Sin[edit]

Returns the sine of a number

Usage

Sin(integer)

Example

msgbox "The sine of 4 is " & sin(4)

Important note!

The input angle for all VB trigometric functions should be in radians. To convert degrees to radians, multiply degrees by pi / 180.

Tan[edit]

Returns the tangent of an angle

Usage

Tan(integer)

Example

msgbox "The tangent of 4 is " & tan(4)

Important note!

The input angle for all VB trigometric functions should be in radians. To convert degrees to radians, multiply degrees by pi / 180.

Val[edit]

Returns the numeric value of a string

Uses "." as decimal separator. ( It does not depend on the Regional Settings )

Usage

Val(string)

Example

Val("5")

The return value will be 5

Val("10.6")

The return value will be 10.6

Val("Hello World")

The return value will be 0 (zero)

txtOutput.Text = Val(txtNumber1.Text) * Val(txtNumber2.Text)

The text box txtOutput will contain the product of the numbers in the txtNumber1 and txtNumber2 text boxes. If either of the text boxes contains a value that cannot be evaluated to a number then the output will be 0 (zero).

Rnd[edit]

Returns a floating point number less than 1 but greater than or equal to 0.

Usage

Rnd[(number)]

You can change the seed the random number generator uses by providing a value as a parameter e.g. Rnd(500) will use the number 500 as the seed in generating random numbers.

  • If you provide a value less than zero then the same number will be returned by the Rnd() function
  • A value of zero will return the most recently generated random number.
  • Providing no value will generate the next random number in the sequence.
  • Providing a positive number will generate the next random number in the sequence using number as a seed.

Example

myvar = Rnd() * 10

myvar will become a random number between 0 and 10.

myvar = (Rnd() * 15) + 25

myvar will become a random number between 25 and 40.

myvar = (Rnd(12345) * 50) - 25

myvar will become a random number between -25 and 25 and 12345 will be used as the seed to generate this number.

Int[edit]

Returns the integer portion of a number.

Usage

Int(n)

Where n is the number to return

Example

Int(10)

Returns 10

Int(5.1)

Returns 5

Int(5.86)

Returns 5

MsgBox "The integer portion of " & myvar & " is " & Int(myvar) & "."

NOTE: No rounding will be performed, the decimal portion of the number will simply be removed. If you want to round a number to the nearest whole integer then use CInt. One interesting point to remember about CInt is that if the decimal portion of the number is exactly .5 then it will be rounded down if the number is odd and rounded up if it is even. For example CInt(1.5) and CInt(2.5) will both return 2.

Input and output[edit]

MsgBox[edit]

The MsgBox function displays a message in a dialog box, waits for the user to click a button, and returns an Integer value indicating which button the user clicked.


Syntax
MsgBox(prompt[, buttons] [, title] [, helpfile, context])

The MsgBox function syntax has these parts:

PART DESCRIPTION
prompt Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.
buttons Optional. Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If omitted, the default value for buttons is 0 (which causes only an OK button to be displayed with no icon).
title Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
helpfile Optional. This argument is only applicable when a Help file has been set up to work with the application.
context Optional. This argument is only applicable when a Help file has been set up to work with the application.


Usage
MsgBox(prompt[, buttons] [, title] [, helpfile, context])
or
Response=MsgBox(prompt[, buttons] [, title] [, helpfile, context])
The integer value of the button selected will be placed into the Response variable.

Button Combinations
vbOKOnly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel

Icon Display
vbCritical
vbQuestion
vbExclamation
vbInformation

Default Button
vbDefaultButton1
vbDefaultButton2
vbDefaultButton3
vbDefaultButton4

Examples
MsgBox "An error has occurred!",vbExclamation,"Error"
Note that since the message is fixed, quotation marks have been used.

Response=MsgBox("Yes or no?",vbYesNo + vbQuestion,"Choose one")
Note the parenthesis and how the vbYesNo and vbQuestion constants have been combined

MsgBox "An error has occurred on line " & lineno, vbExclamation, "Error"

InputBox[edit]

Displays a simple input box for user to enter data

Usage

Variable=InputBox(Prompt,Title)

Variable = variable to which the input value will be stored Prompt = text displayed to the user in the input box Title = title of the input box

Examples

myint=InputBox("Enter a number","Enter a number")

Date and Time[edit]

Date[edit]

Returns or sets the current system date

Example

MsgBox "Today 's date is " & Date & "."

Time[edit]

Returns or sets the current system time

Example

MsgBox "The time now is " & Time & "."


Sidenote: be wary of changing date and time in your program. Many other programs will depend upon the system's date and time being set correctly, so altering it could have a knock on effect. Use date and time changes sparingly, and notify the user if this is being done.

Timer[edit]

Returns the number of seconds since midnight

Example

NumHrs=Int(Timer / 3600) MsgBox "Currently in hour " & NumHrs

WeekdayName[edit]

Returns the name of a day of the week

Usage

WeekdayName(x,FirstDayOfWeek)

x = integer between 1 and 7 FirstDayOfWeek (OPTIONAL) = the day counted as the first in the week. The default is Sunday.

Example

DayName=WeekdayName(i,vbMonday)

Miscellaneous[edit]

IsNull[edit]

Returns true if an expression is null and false otherwise.

Example:

If IsNull(vntMyVariantVar) Then
    Debug.Print "vntMyVariantVar is null"
Else
    Debug.Print "vntMyVariantVar is NOT null"
End If

File Handling[edit]

Open[edit]

Open "" & namefile& ".dat" For Binary As #ff

Selection[edit]

If... Then... Else... Performs selection based upon criteria. A cornerstone of any VB program.

'Usage'

Single Line Selection

If condition Then action

Note that only one line can be used with this style of statement

Multi Line Selection

If condition Then

[code to execute if condition is true]

EndIf

Using Else

If condition Then

[code to execute if condition is true]

Else

[code to execute if condition is false]

EndIf

Condition is a condition which must be met for the code within the statement to be executed. It can make use of the modifiers AND, NOT, OR and XOR (e.g. x=4 AND y > 6). See also the Examples section.

Examples[edit]

Simple one-line selection:

If x < 10 then MsgBox "The number is below 10"

Slightly more complex one-line selection, using the AND modifier to check two conditions at one time.

If x > 10 AND x < 20 then MsgBox "The number is between 10 and 20"

Simple multi-line selection. The code between the If... and EndIf statements will be executed only if the condition is met.

If Date = 25/12/2006 Then
    MsgBox "The date is Christmas Day"
    Call ChristmasDay
EndIf

Using the Else statement. If the variable i is over 4, the program will exit the subroutine. Otherwise, it will go to the label SaveFile.

If i > 4 Then
    Exit Sub
Else
    Goto SaveFile
EndIf

Two If... Endif statements are used, one nested within the other. If i is 6 or 7, the code between the inside If...Endif statements is executed. Then if i=7 the first message box will be shown; otherwise (i.e. if i=6) the other will be displayed. For both cases, the final message box will be shown. When nesting selection statements, it's often a good idea to indent them as shown here.

If i = 6 OR i = 7 Then
   If i = 7 Then
       MsgBox "Today is Sunday"
   Else
       MsgBox "Today is Saturday"
   EndIf
   MsgBox "Today is the Weekend"
EndIf


Previous: Selected Functions Contents Next: Glossary