Visual Basic 6 Cheat Sheet
Classic VB6 syntax including variable declarations, conditionals, loops, and procedures for legacy Windows desktop applications.
Variables & Constants
Declaring typed variables and constants.
Dim strName As StringDim intCount As IntegerDim dblPrice As DoubleDim blnActive As BooleanConst MAX_VALUE As Integer = 100strName = "World"MsgBox "Hello, " & strName & "!"
Control Flow
If statements and Select Case.
If x > 0 Then MsgBox "Positive"ElseIf x < 0 Then MsgBox "Negative"Else MsgBox "Zero"End IfSelect Case grade Case "A" MsgBox "Excellent" Case "B", "C" MsgBox "Good" Case Else MsgBox "Needs improvement"End Select
Loops
For, Do While, and Do Until loops.
For i = 1 To 10 Debug.Print iNext iFor i = 10 To 1 Step -1 Debug.Print iNext iDo While x < 10 x = x + 1LoopDo Until x = 0 x = x - 1Loop
Subs, Functions & Arrays
Reusable procedures and array declarations.
Sub Greet(name As String) MsgBox "Hello, " & nameEnd SubFunction Square(x As Double) As Double Square = x * xEnd FunctionDim arr(1 To 5) As IntegerDim dynArr() As StringReDim dynArr(10)ReDim Preserve dynArr(20)
Error Handling
On Error trapping with the Err object and cleanup labels.
Private Sub SaveData() On Error GoTo ErrHandler Dim f As Integer f = FreeFile Open "data.txt" For Output As #f Print #f, "hello" Close #f Exit SubErrHandler: MsgBox "Error " & Err.Number & ": " & Err.Description If f > 0 Then Close #fEnd Sub
User Types & Collections
Type structures and the Collection object for keyed storage.
Private Type Person Name As String Age As IntegerEnd TypeDim p As Personp.Name = "Ann": p.Age = 30Dim col As New Collectioncol.Add p, p.Name ' key = NameDim item As Personitem = col("Ann")MsgBox col.Count & " items"col.Remove "Ann"
String & Conversion Functions
Built-in functions for text and type conversion.
- Len(s) / Mid(s, start, n)- string length and substring extraction (1-based)
- Left / Right- take n characters from the start or end of a string
- InStr(start, s, find)- position of a substring, 0 if not found
- Replace(s, find, repl)- substitute all occurrences of a substring
- Trim / LTrim / RTrim- remove leading and/or trailing spaces
- UCase / LCase- convert case
- CInt / CLng / CDbl / CStr- explicit type conversion functions
- Val / Str- parse a number from text and format a number as text
File I/O
Sequential and free-file based reading and writing.
Dim f As Integer, line As Stringf = FreeFileOpen "input.txt" For Input As #fDo While Not EOF(f) Line Input #f, line Debug.Print lineLoopClose #f' Check existence before openingIf Dir("input.txt") <> "" Then MsgBox "exists"
Put `Option Explicit` at the top of every module — without it VB6 silently creates a new Variant variable on any misspelled name, which is one of the most common sources of hard-to-find bugs in legacy VB6 code.