Visual Basic 6 (1998) and Visual Basic for Applications (the macro language of Microsoft Office and some other programs) are the same language engine: a COM-based, interpreted-or-compiled language with Variant, Set and Property Let, and no inheritance. Their source files are text. A standard module (.bas) holds procedures and data; a class module (.cls) is a class; forms, user controls and similar designers (.frm, .ctl …) have a header and are on the next page. The extensions are shared with other formats: a .bas may be a QuickBASIC or another BASIC program, and a .cls a LaTeX class, a Salesforce Apex class or a Caché ObjectScript class, which is why the viewer looks at the text first.
The shape of a file
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "Dictionary"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Option Explicit
#Const UseScriptingDictionaryIfAvailable = True
Private dict_pCompareMode As CompareMethod
Public Enum CompareMethod
BinaryCompare = VBA.vbBinaryCompare
TextCompare = VBA.vbTextCompare
End Enum
Public Property Get CompareMode() As CompareMethod
Attribute CompareMode.VB_Description = "Set or get the string comparison method."
CompareMode = dict_pCompareMode
End Property
Attribute lines, options, directives, declarations and a procedure.- The header appears in
.cls(and form) files only:VERSION 1.0 CLASS, then aBEGIN … ENDblock of class properties (MultiUse,Persistable,DataBindingBehavior,DataSourceBehavior,MTSTransactionMode; the value-1is True and a comment after the line gives the readable form). A standard module has none. Attributelines hold settings the editor keeps out of the code window and writes at the top of the exported file (and after a procedure’s heading, for that procedure):VB_Name(the module’s name),VB_GlobalNameSpace,VB_Creatable,VB_PredeclaredId(a class with a default instance, like a form),VB_Exposed(public outside the project),VB_Description,VB_UserMemId(0makes a member the default member of the class),VB_VarHelpID,VB_ProcData.VB_Invoke_Func. The editor strips them on import, so they exist only in files.- Then the code:
Optionstatements first, then the declarations of the module, then the procedures. Comments start with'orRemand run to the end of the line; a line continues with a space and an underscore as its last character (a comment cannot be continued); a colon separates statements; a statement may have a numeric line label or aName:label.
Declarations and types
Option Explicit
Option Base 1
Option Compare Text
Option Private Module
Private Const MaxItems As Long = 100
Public Counter As Integer
Dim buffer(1 To 10) As Double
Private names() As String
Private Type Point
X As Long
Y As Long
End Type
Private Declare PtrSafe Function GetTickCount Lib "kernel32" () As Long
Private WithEvents sheet As Worksheet
DefInt A-C
| Type | Size and range (VBA documentation) |
|---|---|
Boolean | 2 bytes, True (−1) or False (0) |
Byte | 1 byte, 0 to 255 |
Integer | 2 bytes, −32,768 to 32,767 (not 32-bit as in .NET) |
Long | 4 bytes, −2,147,483,648 to 2,147,483,647 |
LongLong | 8 bytes, 64-bit platforms only |
LongPtr | 4 bytes on 32-bit, 8 bytes on 64-bit systems: handles and pointers |
Single, Double | 4 and 8 bytes, floating point |
Currency | 8 bytes, a scaled integer with four decimal places (±922,337,203,685,477.5807) |
Decimal | 14 bytes; exists only inside a Variant (a Dim of Decimal is not allowed) |
Date | 8 bytes, from 1 January 100 to 31 December 9999 |
String | variable length (about 2 billion characters) or fixed length (String * 10, up to about 65,400) |
Object | a reference to any object; Collection and Dictionary are object types |
Variant | 16 bytes for a number, 22 plus the length for text; holds any value, and also Empty (not initialised), Null (no valid data) and Error; the default type of a declaration without As |
| user-defined | a Type … End Type block of fields; an Enum … End Enum block gives named Long constants |
Dim declares a variable of a procedure or module; Private and Public (older: Global) declare module-level ones; Static keeps a local between calls; Const makes a constant. Dim a(1 To 10) gives explicit bounds (Dim a(10) has bounds 0 to 10, 11 elements, unless Option Base 1). Deftype statements (DefInt A-C, DefStr S, DefLng, DefBool, DefByte, DefCur, DefDate, DefDbl, DefObj, DefSng, DefVar, DefLngLng, DefLngPtr) make undeclared names beginning with those letters that type. Type characters % & ^ ! # @ $ (^ is LongLong) may end a name or a number.
Procedures, classes and events
Public Property Get Count() As Long
Count = m_count
End Property
Public Property Let Count(ByVal Value As Long)
m_count = Value
End Property
Public Property Set Owner(ByVal Value As Object)
Set m_owner = Value
End Property
Public Event Changed(ByVal NewValue As Long)
Private Sub Class_Initialize()
Set m_owner = Nothing
End Sub
Public Function Find(ByVal key As String, Optional ByVal start As Long = 1) As Long
Dim i As Long
For i = start To UBound(m_keys)
If m_keys(i) = key Then
Find = i ' the result is assigned to the name
Exit Function
End If
Next i
Find = -1
End Function
Get, Let and Set, an event, the class constructor and a function.- Procedures:
Sub,Function(the result is assigned to the function’s name) andProperty Get,Property Let(a value) andProperty Set(an object);Public,PrivateorFriendandStatic. Parameters areByRefby default (the opposite of .NET), may beByVal,Optional(with a default, or tested withIsMissingon aVariant) orParamArray. A call isFoo(a, b)in an expression, but as a statement eitherCall Foo(a, b)orFoo a, bwith no brackets. - Objects:
Set x = New FooorSet x = otherassign object references; plainx = yassigns the default member’s value (Let, optional).Nothingclears a reference, andIf x Is Nothingtests it.Dim x As New Foocreates the object on first use. - Classes have no inheritance; they implement interfaces with
Implements IFoo(then every member of the interface is written asIFoo_Member).Class_InitializeandClass_Terminateare the constructor and destructor. - Events:
Public Event Name(args)declares one,RaiseEvent Name(args)raises it, and aWithEventsvariable receives it in a procedure namedvariable_Name; the form and control events (Form_Load,Command1_Click) work the same way. - Declare:
Declare Function Name Lib "library" Alias "entry" (args) As Typeimports a native function; withPtrSafeandLongPtr(theVBA7compilation constant, Office 2010 and later) it is also valid in 64-bit Office, and the compilation constantsWin64,Win32andMacselect code by platform in#Ifblocks.
Statements
Sub Demo(path As String)
Dim n As Long, f As Integer, line As String
On Error GoTo Handler
f = FreeFile
Open path For Input As #f
Do While Not EOF(f)
Line Input #f, line
n = n + 1
Debug.Print n; line
Loop
Close #f
Select Case n
Case 0: MsgBox "empty"
Case 1 To 9: MsgBox "short"
Case Else: MsgBox "long"
End Select
With ActiveSheet.Range("A1")
.Value = n
End With
Exit Sub
Handler:
MsgBox "Error " & Err.Number & ": " & Err.Description
Resume Next
End Sub
Select Case, With and error handling in VBA.| Kind | Statements |
|---|---|
| flow | If … Then … ElseIf … Else … End If (and the single-line form), Select Case, For … Next with Step, For Each … Next, Do … Loop with While or Until at either end, While … Wend, GoTo, GoSub … Return, On … GoTo, On … GoSub, Exit For|Do|Sub|Function|Property, End, Stop, With |
| errors | On Error GoTo label, On Error GoTo 0, On Error Resume Next, Resume, Resume Next, Resume label, Error n, the Err object (Number, Description, Source, Raise, Clear) |
| assignment | x = e, Let x = e, Set obj = ref, Mid(s, a, n) = t, LSet, RSet (there is no +=) |
| declaration | Dim, ReDim [Preserve], Erase, Const, Static, Public, Private, Type, Enum, Declare, Event, Implements, Option …, Def… |
| files | Open … For Input|Output|Append|Binary|Random [Access Read|Write|Read Write] [Shared|Lock Read|Lock Write|Lock Read Write] As #n [Len = n], Close, Print #, Write #, Input #, Line Input #, Get #, Put #, Seek #, Lock, Unlock, Reset, Width #, Name … As …, Kill, MkDir, RmDir, ChDir, ChDrive, FileCopy, SetAttr |
| other | Call, RaiseEvent, Randomize, Beep, DoEvents, AppActivate, SendKeys, Load, Unload, Date = , Time = , SaveSetting, DeleteSetting, Rem |
The operators are ^ * / \ Mod + - &, the comparisons = <> < > <= >= Like Is and the logical operators Not And Or Xor Eqv Imp (bitwise on numbers; there is no short-circuit AndAlso). The library is the VBA library (VBA.Strings, VBA.Math, VBA.DateTime, VBA.Interaction, VBA.FileSystem, VBA.Conversion) listed on the standard library page, with host objects (Application, ActiveSheet) and the Debug object (Debug.Print, Debug.Assert).
Against Visual Basic .NET
| Point | VB6 and VBA | Visual Basic .NET |
|---|---|---|
| Integer and Long | 16 and 32 bits | 32 and 64 bits (Short is 16) |
| Untyped declaration | Variant | Object (or an inferred type) |
| Parameters | ByRef by default | ByVal by default |
| Object assignment | Set x = obj, and Let for values | plain x = obj |
| Properties | Property Get / Let / Set | Property … Get / Set |
| Inheritance | none (interfaces only) | Inherits |
| Short-circuit operators | none | AndAlso, OrElse |
| Loops | While … Wend | While … End While |
| Calls | Foo a, b without brackets as a statement | brackets always |
| Source files | modules with Attribute lines and form headers | namespaces and plain declarations |
Not described
Known, not yet covered
- Reference: the Open Specifications document [MS-VBAL] (the specification of the VBA language) and the Visual Basic 6 language reference could not be fetched in this pass: the published addresses of the specification returned errors from this machine and the VB6 documentation is not in a public repository. This page is written from Microsoft’s VBA language reference (the Markdown sources of MicrosoftDocs/VBA-Docs, read for the data types, keywords, statements and functions), from the real VBA and VB6 files listed on the overview and from knowledge of the languages. No example here was run (no VBA or VB6 host was available).
- Reference: the formal grammar and the lexical details (the exact rules for line labels, type characters on numbers,
Remafter a colon, any limit on the number of continuations, date literals), the Variant conversion rules, the VB6-only features (control arrays,Declarealiases by ordinal,Optionalwithout a default for non-Variants, ActiveX and theApp,ScreenandPrinterobjects) and the VBA host object models are not described. - Viewer: the file statements (
Open,Print,Input,Line…) are coloured as keywords only at the start of a statement; a procedure calledPrintwith a bracket, or a variable calledNamethat is assigned to, is not coloured as one.
See also
- VB6 forms and projects – the form header,
.frmand.vbpfiles - VBScript – the scripting subset
- Versions and history