VB Visual Basic 6

VB6 Language Reference

WebVB Studio supports classic Visual Basic 6 syntaxβ€”the same language that powered millions of desktop applications. Write familiar code with modern web capabilities.

πŸ“˜
Classic Syntax
Familiar VB6 code style
⚑
Instant Run
No compilation needed
🌐
Web Enhanced
Modern web APIs

Variables and Data Types

Declaring Variables
' Declare with explicit type
Dim name As String
Dim age As Integer
Dim price As Double
Dim isActive As Boolean
Dim birthDate As Date

' Declare and assign
Dim message As String
message = "Hello, World!"

' Multiple declarations
Dim x As Integer, y As Integer, z As Integer

' Module-level (accessible across all procedures)
Private counter As Integer
Public sharedValue As String

Data Types

Type Description Example
String Text of any length "Hello World"
Integer Whole numbers (-32,768 to 32,767) 42
Long Large whole numbers 2147483647
Single Single-precision decimal 3.14
Double Double-precision decimal 3.14159265359
Boolean True or False True
Date Date and time values #12/25/2024#
Variant Any type (flexible) anything
Object Reference to objects Set obj = ...

Operators

βž• Arithmetic

Additiona + b
Subtractiona - b
Multiplicationa * b
Divisiona / b
Integer Divisiona \ b
Moduloa Mod b
Exponenta ^ b

βš–οΈ Comparison

Equala = b
Not Equala <> b
Less Thana < b
Greater Thana > b
Less or Equala <= b
Greater or Equala >= b

πŸ”€ Logical

Anda And b
Ora Or b
NotNot a
Xora Xor b

πŸ“ String

Concatenate"Hello" & " World"
Also concat"Hello" + " World"
Comparea Like "pattern"

Control Structures

If...Then...Else

' Simple If
If score >= 60 Then
    lblResult.Caption = "Pass"
End If

' If...Else
If age >= 18 Then
    lblStatus.Caption = "Adult"
Else
    lblStatus.Caption = "Minor"
End If

' If...ElseIf...Else
If grade >= 90 Then
    lblGrade.Caption = "A"
ElseIf grade >= 80 Then
    lblGrade.Caption = "B"
ElseIf grade >= 70 Then
    lblGrade.Caption = "C"
Else
    lblGrade.Caption = "F"
End If

' Single-line If
If x > 0 Then lblSign.Caption = "Positive"

Select Case

Select Case dayOfWeek
    Case 1
        lblDay.Caption = "Sunday"
    Case 2
        lblDay.Caption = "Monday"
    Case 3, 4, 5
        lblDay.Caption = "Midweek"
    Case 6 To 7
        lblDay.Caption = "Weekend"
    Case Else
        lblDay.Caption = "Invalid"
End Select

Loops

For...Next
' Count 1 to 10
For i = 1 To 10
    lstNumbers.AddItem i
Next i

' Count down
For i = 10 To 1 Step -1
    Debug.Print i
Next i

' Step by 2
For i = 0 To 100 Step 2
    ' Even numbers only
Next i
Do...Loop
' While condition
Do While x < 100
    x = x + 1
Loop

' Until condition
Do Until found = True
    found = Search()
Loop

' Loop at least once
Do
    answer = InputBox("Enter Y")
Loop Until answer = "Y"

For Each

' Iterate through collection
Dim item As Variant
For Each item In myCollection
    Debug.Print item
Next item

' Iterate through controls on form
Dim ctrl As Control
For Each ctrl In Me.Controls
    If TypeOf ctrl Is TextBox Then
        ctrl.Text = ""
    End If
Next ctrl

Procedures and Functions

Sub Procedures (No Return Value)
' Simple Sub
Private Sub ShowMessage()
    MsgBox "Hello!"
End Sub

' Sub with parameters
Private Sub Greet(name As String)
    lblGreeting.Caption = "Hello, " & name & "!"
End Sub

' Sub with ByRef parameter (modifies original)
Private Sub DoubleIt(ByRef value As Integer)
    value = value * 2
End Sub

' Sub with ByVal parameter (copy, original unchanged)
Private Sub ProcessCopy(ByVal value As Integer)
    value = value + 10  ' Only affects local copy
End Sub
Functions (Return Value)
' Simple Function
Private Function Add(a As Integer, b As Integer) As Integer
    Add = a + b
End Function

' Using the function
Dim result As Integer
result = Add(5, 3)  ' result = 8

' Function with optional parameter
Private Function FormatName(firstName As String, Optional lastName As String = "") As String
    If lastName = "" Then
        FormatName = firstName
    Else
        FormatName = firstName & " " & lastName
    End If
End Function

' Boolean function
Private Function IsEven(num As Integer) As Boolean
    IsEven = (num Mod 2 = 0)
End Function

Event Handlers

Event handlers respond to user actions. They follow the pattern: ControlName_EventName()

' Button click
Private Sub cmdSubmit_Click()
    MsgBox "Form submitted!"
End Sub

' Form load (initialization)
Private Sub Form_Load()
    Me.Caption = "My Application"
    txtName.Text = ""
    cboOptions.AddItem "Option 1"
    cboOptions.AddItem "Option 2"
End Sub

' Text changed
Private Sub txtInput_Change()
    lblLength.Caption = "Length: " & Len(txtInput.Text)
End Sub

' Key press (with parameter)
Private Sub txtInput_KeyPress(KeyAscii As Integer)
    ' Only allow numbers
    If KeyAscii < 48 Or KeyAscii > 57 Then
        KeyAscii = 0  ' Cancel the key
    End If
End Sub

' Timer event
Private Sub Timer1_Timer()
    lblTime.Caption = Time
End Sub

' Mouse events
Private Sub Canvas1_MouseMove(X As Single, Y As Single)
    lblCoords.Caption = "X: " & X & ", Y: " & Y
End Sub

Common Events

Event Triggered When Parameters
Click User clicks the control None
DblClick User double-clicks None
Change Value/text changes None
KeyPress Key is pressed KeyAscii As Integer
KeyDown/KeyUp Key down/released KeyCode, Shift
MouseMove Mouse moves over control X, Y, Button, Shift
MouseDown/Up Mouse button pressed/released Button, Shift, X, Y
GotFocus Control receives focus None
LostFocus Control loses focus None
Timer Timer interval elapses None

Built-in Functions

πŸ“ String Functions

Dim s As String
s = "Hello World"

Len(s)              ' 11 - Length
Left(s, 5)          ' "Hello" - Left characters
Right(s, 5)         ' "World" - Right characters
Mid(s, 7, 5)        ' "World" - Substring
UCase(s)            ' "HELLO WORLD" - Uppercase
LCase(s)            ' "hello world" - Lowercase
Trim(s)             ' Remove leading/trailing spaces
LTrim(s)            ' Remove leading spaces
RTrim(s)            ' Remove trailing spaces
InStr(s, "World")   ' 7 - Find position
Replace(s, "World", "VB")  ' "Hello VB"
Split(s, " ")       ' Array: ["Hello", "World"]
Join(arr, "-")      ' "Hello-World"
StrReverse(s)       ' "dlroW olleH"
String(5, "*")      ' "*****" - Repeat character
Space(10)           ' "          " - Spaces

πŸ”’ Numeric Functions

Abs(-5)             ' 5 - Absolute value
Int(3.7)            ' 3 - Integer part (toward negative)
Fix(3.7)            ' 3 - Integer part (toward zero)
Round(3.567, 2)     ' 3.57 - Round to decimals
Sgn(-10)            ' -1 - Sign (-1, 0, or 1)
Sqr(16)             ' 4 - Square root
Exp(1)              ' 2.718... - e^x
Log(10)             ' 2.302... - Natural log
Sin(x), Cos(x), Tan(x)  ' Trigonometry
Atn(x)              ' Arctangent
Rnd                 ' Random 0-1
Randomize           ' Seed random generator

' Generate random integer 1-100
Randomize
num = Int(Rnd * 100) + 1

πŸ”„ Conversion Functions

Val("123")          ' 123 - String to number
Str(123)            ' "123" - Number to string
CStr(123)           ' "123" - Convert to String
CInt("42")          ' 42 - Convert to Integer
CLng("1000000")     ' 1000000 - Convert to Long
CDbl("3.14")        ' 3.14 - Convert to Double
CBool(1)            ' True - Convert to Boolean
CDate("12/25/2024") ' Date value
Asc("A")            ' 65 - Character to ASCII
Chr(65)             ' "A" - ASCII to character
Hex(255)            ' "FF" - To hexadecimal
Oct(8)              ' "10" - To octal

πŸ“… Date/Time Functions

Now                 ' Current date and time
Date                ' Current date
Time                ' Current time
Year(Now)           ' 2024
Month(Now)          ' 12
Day(Now)            ' 25
Hour(Now)           ' 14
Minute(Now)         ' 30
Second(Now)         ' 45
Weekday(Now)        ' 1-7 (Sunday=1)
WeekdayName(1)      ' "Sunday"
MonthName(12)       ' "December"

DateAdd("d", 7, Now)      ' Add 7 days
DateAdd("m", 1, Now)      ' Add 1 month
DateAdd("yyyy", 1, Now)   ' Add 1 year

DateDiff("d", date1, date2)  ' Days between dates
DateDiff("yyyy", birthDate, Now)  ' Calculate age

Format(Now, "mm/dd/yyyy")     ' "12/25/2024"
Format(Now, "hh:mm:ss AM/PM") ' "02:30:45 PM"

Arrays

' Fixed-size array
Dim numbers(10) As Integer     ' 0 to 10 (11 elements)
Dim matrix(5, 5) As Double     ' 2D array

' Dynamic array
Dim items() As String
ReDim items(5)                 ' Resize to 6 elements
ReDim Preserve items(10)       ' Resize, keep values

' Array with specific bounds
Dim months(1 To 12) As String

' Initialize array
numbers(0) = 10
numbers(1) = 20

' Array functions
LBound(numbers)     ' Lower bound (usually 0)
UBound(numbers)     ' Upper bound
Erase numbers       ' Clear/reset array

' Array from string
Dim parts() As String
parts = Split("a,b,c", ",")    ' ["a", "b", "c"]

' Loop through array
For i = LBound(arr) To UBound(arr)
    Debug.Print arr(i)
Next i

Error Handling

' Basic error handling
On Error GoTo ErrorHandler

Dim result As Double
result = Val(txtInput.Text) / Val(txtDivisor.Text)
lblResult.Caption = result
Exit Sub

ErrorHandler:
    MsgBox "Error: " & Err.Description
    Resume Next  ' Continue with next line

' Inline error handling
On Error Resume Next
result = 10 / 0
If Err.Number  0 Then
    MsgBox "Cannot divide by zero"
    Err.Clear
End If
On Error GoTo 0  ' Disable error handling

' Error object properties
Err.Number       ' Error number
Err.Description  ' Error message
Err.Source       ' Source of error
Err.Clear        ' Clear the error

Message Boxes and Input

' Simple message
MsgBox "Hello World!"

' With title
MsgBox "Operation complete", vbInformation, "Success"

' With buttons and check result
Dim response As Integer
response = MsgBox("Save changes?", vbYesNoCancel + vbQuestion, "Confirm")

If response = vbYes Then
    ' Save
ElseIf response = vbNo Then
    ' Don't save
Else
    ' Cancel
End If

' Button constants
vbOKOnly        ' OK button only
vbOKCancel      ' OK and Cancel
vbYesNo         ' Yes and No
vbYesNoCancel   ' Yes, No, and Cancel
vbRetryCancel   ' Retry and Cancel

' Icon constants
vbCritical      ' Error icon
vbQuestion      ' Question mark
vbExclamation   ' Warning icon
vbInformation   ' Info icon

' Input box
Dim name As String
name = InputBox("Enter your name:", "Name Input", "Default")
If name  "" Then
    lblGreeting.Caption = "Hello, " & name
End If

Common Patterns

Form Validation

Private Sub cmdSubmit_Click()
    If Trim(txtName.Text) = "" Then
        MsgBox "Name is required"
        txtName.SetFocus
        Exit Sub
    End If
    If Not IsNumeric(txtAge.Text) Then
        MsgBox "Age must be a number"
        Exit Sub
    End If
    ' Process form...
End Sub

Loading ComboBox

Private Sub Form_Load()
    cboCountry.Clear
    cboCountry.AddItem "USA"
    cboCountry.AddItem "Canada"
    cboCountry.AddItem "UK"
    cboCountry.ListIndex = 0  ' Select first item
End Sub

Timer-based Animation

Private Sub Form_Load()
    Timer1.Interval = 50
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Timer()
    Shape1.Left = Shape1.Left + 5
    If Shape1.Left > Me.Width Then
        Shape1.Left = 0
    End If
End Sub