Visual Basic
Programming Language
Visual Basic
Overview
Visual Basic is an event-driven programming language developed by Microsoft, widely used for Windows GUI application development.
Details
Visual Basic is an event-driven programming language announced by Microsoft in 1991. Based on the BASIC language, it provided a visual programming environment (RAD: Rapid Application Development) designed for efficient development of Windows GUI applications. With drag-and-drop user interface design, intuitive syntax, and rich control libraries, even programming beginners could create Windows applications relatively easily. Visual Basic 6.0 (VB6) was the last classic version, which then evolved into VB.NET based on the .NET Framework. Currently, maintenance of legacy systems is more central than new development, but it continues to operate in many enterprise systems.
Usage Examples
Hello World
' Classic Visual Basic (VB6) example
' Click event for a command button placed on a form
Private Sub Command1_Click()
MsgBox "Hello, World!"
End Sub
' Execution in Immediate Window
' (Can be executed in VB Editor's Immediate Window)
Sub HelloWorldImmediate()
Debug.Print "Hello, World!"
End Sub
' Defined as a procedure
Public Sub HelloWorld()
MsgBox "Hello, World!", vbInformation, "Greeting"
End Sub
' Execution in Form Load event
Private Sub Form_Load()
Me.Caption = "Hello, World! Application"
Label1.Caption = "Hello, Visual Basic!"
End Sub
' Multi-line message
Private Sub ShowMultiLineMessage()
Dim message As String
message = "Hello, World!" & vbCrLf & _
"Welcome to Visual Basic!" & vbCrLf & _
"GUI application development is easy."
MsgBox message, vbInformation, "Multi-line Message"
End Sub
' Console application style example (actually using textbox on form)
Private Sub ConsoleStyleHello()
Text1.Text = Text1.Text & "Hello, World!" & vbCrLf
Text1.Text = Text1.Text & "Current time: " & Now() & vbCrLf
Text1.Text = Text1.Text & "Created with Visual Basic" & vbCrLf
End Sub
' Example using input dialog
Private Sub InteractiveHello()
Dim userName As String
userName = InputBox("Please enter your name:", "Name Input", "Guest")
If userName <> "" Then
MsgBox "Hello, " & userName & "!", vbInformation, "Personal Greeting"
Else
MsgBox "No name was entered.", vbExclamation, "Warning"
End If
End Sub
' Example using loops
Private Sub RepeatedHello()
Dim i As Integer
Dim message As String
For i = 1 To 5
message = message & "Hello " & i & " times!" & vbCrLf
Next i
MsgBox message, vbInformation, "Repeated Greeting"
End Sub
Variables and Data Types
' Basic variable declaration
Private Sub VariableBasics()
' Basic data types
Dim studentName As String
Dim age As Integer
Dim height As Single
Dim weight As Double
Dim isActive As Boolean
Dim birthDate As Date
' Value assignment
studentName = "John Doe"
age = 25
height = 175.5
weight = 68.5
isActive = True
birthDate = #12/25/1998#
' Declaration with initialization
Dim score As Integer = 85
Dim grade As String = "A"
' Display results
Debug.Print "Name: " & studentName
Debug.Print "Age: " & age
Debug.Print "Height: " & height & "cm"
Debug.Print "Weight: " & weight & "kg"
Debug.Print "Active: " & isActive
Debug.Print "Birth Date: " & birthDate
Debug.Print "Score: " & score
Debug.Print "Grade: " & grade
End Sub
' Numeric data type details
Private Sub NumericTypes()
' Integer types
Dim byteValue As Byte ' 0-255
Dim integerValue As Integer ' -32,768 to 32,767
Dim longValue As Long ' -2,147,483,648 to 2,147,483,647
' Floating point types
Dim singleValue As Single ' Single precision floating point
Dim doubleValue As Double ' Double precision floating point
' Currency type
Dim currencyValue As Currency ' Fixed-point numeric (for currency calculations)
' Value assignment
byteValue = 255
integerValue = -12345
longValue = 1234567890
singleValue = 3.14159
doubleValue = 3.141592653589793
currencyValue = 1234.56
' Display
Debug.Print "Byte: " & byteValue
Debug.Print "Integer: " & integerValue
Debug.Print "Long: " & longValue
Debug.Print "Single: " & singleValue
Debug.Print "Double: " & doubleValue
Debug.Print "Currency: " & Format(currencyValue, "Currency")
End Sub
' String operations
Private Sub StringOperations()
Dim firstName As String
Dim lastName As String
Dim fullName As String
Dim message As String
firstName = "John"
lastName = "Smith"
' String concatenation
fullName = lastName & " " & firstName
' Using string functions
Debug.Print "Full Name: " & fullName
Debug.Print "Length: " & Len(fullName)
Debug.Print "Uppercase: " & UCase(fullName)
Debug.Print "Lowercase: " & LCase(fullName)
Debug.Print "Left 3 chars: " & Left(fullName, 3)
Debug.Print "Right 2 chars: " & Right(fullName, 2)
Debug.Print "2 chars from position 3: " & Mid(fullName, 3, 2)
' String search
If InStr(fullName, "Smith") > 0 Then
Debug.Print "Last name is Smith"
End If
' String replacement
message = Replace(fullName, "Smith", "Johnson")
Debug.Print "After replacement: " & message
End Sub
' Array usage
Private Sub ArrayExamples()
' Static arrays
Dim numbers(1 To 5) As Integer
Dim fruits(3) As String ' 0 to 3 (4 elements)
' Value assignment
numbers(1) = 10
numbers(2) = 20
numbers(3) = 30
numbers(4) = 40
numbers(5) = 50
fruits(0) = "apple"
fruits(1) = "banana"
fruits(2) = "orange"
fruits(3) = "strawberry"
' Dynamic arrays
Dim scores() As Integer
ReDim scores(1 To 10) ' Dynamically set size
' Set array values
Dim i As Integer
For i = 1 To 10
scores(i) = i * 10
Next i
' Display array contents
Debug.Print "=== Numeric Array ==="
For i = 1 To 5
Debug.Print "numbers(" & i & ") = " & numbers(i)
Next i
Debug.Print "=== String Array ==="
For i = 0 To 3
Debug.Print "fruits(" & i & ") = " & fruits(i)
Next i
Debug.Print "=== Dynamic Array ==="
For i = 1 To 10
Debug.Print "scores(" & i & ") = " & scores(i)
Next i
' Resize array (preserve data)
ReDim Preserve scores(1 To 15)
' Set values for new elements
For i = 11 To 15
scores(i) = i * 5
Next i
End Sub
' Variant data type
Private Sub VariantType()
Dim varValue As Variant
' Store various type values
varValue = "string"
Debug.Print "As string: " & varValue & " (Type: " & TypeName(varValue) & ")"
varValue = 12345
Debug.Print "As number: " & varValue & " (Type: " & TypeName(varValue) & ")"
varValue = #12/25/2023#
Debug.Print "As date: " & varValue & " (Type: " & TypeName(varValue) & ")"
varValue = True
Debug.Print "As boolean: " & varValue & " (Type: " & TypeName(varValue) & ")"
' Can also store arrays
Dim tempArray(2) As String
tempArray(0) = "A"
tempArray(1) = "B"
tempArray(2) = "C"
varValue = tempArray
Debug.Print "As array: " & Join(varValue, ",") & " (Type: " & TypeName(varValue) & ")"
End Sub
' Using constants
Private Sub ConstantExamples()
' Constant declaration
Const PI As Double = 3.14159265359
Const COMPANY_NAME As String = "Sample Corporation"
Const MAX_USERS As Integer = 100
' Usage example
Dim radius As Double
Dim area As Double
radius = 5
area = PI * radius * radius
Debug.Print "Circle radius: " & radius
Debug.Print "Circle area: " & area
Debug.Print "Company name: " & COMPANY_NAME
Debug.Print "Maximum users: " & MAX_USERS
End Sub
Control Structures and Functions
' If statements and Select Case statements
Private Sub ConditionalStatements()
Dim score As Integer
Dim grade As String
score = 85
' If-ElseIf-Else statement
If score >= 90 Then
grade = "A"
ElseIf score >= 80 Then
grade = "B"
ElseIf score >= 70 Then
grade = "C"
ElseIf score >= 60 Then
grade = "D"
Else
grade = "F"
End If
Debug.Print "Score: " & score & ", Grade: " & grade
' Select Case statement
Select Case score
Case 90 To 100
Debug.Print "Excellent"
Case 80 To 89
Debug.Print "Good"
Case 70 To 79
Debug.Print "Average"
Case 60 To 69
Debug.Print "Needs Improvement"
Case Else
Debug.Print "Failed"
End Select
' Select Case with multiple values
Dim dayOfWeek As Integer
dayOfWeek = Weekday(Now)
Select Case dayOfWeek
Case 1, 7 ' Sunday, Saturday
Debug.Print "It's weekend"
Case 2 To 6 ' Monday to Friday
Debug.Print "It's weekday"
End Select
End Sub
' Loop structures
Private Sub LoopStructures()
Dim i As Integer
Dim j As Integer
Dim total As Integer
Debug.Print "=== For Next Loop ==="
For i = 1 To 5
Debug.Print "Count: " & i
Next i
Debug.Print "=== For Loop with Step ==="
For i = 10 To 2 Step -2
Debug.Print "Reverse: " & i
Next i
Debug.Print "=== Do While Loop ==="
i = 1
Do While i <= 3
Debug.Print "Do While: " & i
i = i + 1
Loop
Debug.Print "=== Do Until Loop ==="
i = 1
Do Until i > 3
Debug.Print "Do Until: " & i
i = i + 1
Loop
Debug.Print "=== While Wend Loop ==="
i = 1
While i <= 3
Debug.Print "While Wend: " & i
i = i + 1
Wend
Debug.Print "=== Nested Loops ==="
For i = 1 To 3
For j = 1 To 2
Debug.Print "Outer:" & i & ", Inner:" & j
Next j
Next i
Debug.Print "=== Using Exit Statement ==="
For i = 1 To 10
If i = 5 Then
Debug.Print "Exit at 5"
Exit For
End If
Debug.Print "Value: " & i
Next i
End Sub
' Functions and sub procedures
Private Sub ProcedureExamples()
Dim result As Double
Dim message As String
' Function calls
result = CalculateArea(5)
Debug.Print "Area of circle with radius 5: " & result
result = AddNumbers(10, 20)
Debug.Print "10 + 20 = " & result
' Sub procedure calls
DisplayMessage "Hello"
' Pass by reference example
Dim value1 As Integer
Dim value2 As Integer
value1 = 10
value2 = 20
Debug.Print "Before swap: value1=" & value1 & ", value2=" & value2
SwapValues value1, value2
Debug.Print "After swap: value1=" & value1 & ", value2=" & value2
' Optional argument example
message = CreateGreeting("Smith")
Debug.Print message
message = CreateGreeting("Johnson", " Jr.")
Debug.Print message
End Sub
' Area calculation function
Private Function CalculateArea(radius As Double) As Double
Const PI As Double = 3.14159265359
CalculateArea = PI * radius * radius
End Function
' Addition function
Private Function AddNumbers(num1 As Double, num2 As Double) As Double
AddNumbers = num1 + num2
End Function
' Message display sub procedure
Private Sub DisplayMessage(msg As String)
Debug.Print "Message: " & msg
End Sub
' Value swapping (pass by reference)
Private Sub SwapValues(ByRef a As Integer, ByRef b As Integer)
Dim temp As Integer
temp = a
a = b
b = temp
End Sub
' Function with optional arguments
Private Function CreateGreeting(name As String, Optional suffix As String = " Sir/Madam") As String
CreateGreeting = "Hello, " & name & suffix
End Function
' Variable argument example (using array)
Private Function SumArray(numbers() As Integer) As Long
Dim i As Integer
Dim total As Long
total = 0
For i = LBound(numbers) To UBound(numbers)
total = total + numbers(i)
Next i
SumArray = total
End Function
' Error handling
Private Sub ErrorHandlingExample()
On Error GoTo ErrorHandler
Dim result As Double
Dim num1 As Double
Dim num2 As Double
num1 = 10
num2 = 0
Debug.Print "Performing division: " & num1 & " ÷ " & num2
result = num1 / num2 ' Division by zero error occurs
Debug.Print "Result: " & result
Exit Sub
ErrorHandler:
Debug.Print "Error occurred: " & Err.Description
Debug.Print "Error number: " & Err.Number
' Resume from error
If Err.Number = 11 Then ' Division error
Debug.Print "Division by zero error detected"
result = 0
Resume Next
Else
Debug.Print "Unexpected error"
Resume ExitPoint
End If
ExitPoint:
Debug.Print "Exiting procedure"
End Sub
Object-Oriented Programming and GUI Operations
' Class module example (separate file: Person.cls)
' Class: Person
' Class with properties and methods
'Private mName As String
'Private mAge As Integer
'Private mEmail As String
' Property (Name)
'Public Property Get Name() As String
' Name = mName
'End Property
'Public Property Let Name(value As String)
' mName = value
'End Property
' Property (Age)
'Public Property Get Age() As Integer
' Age = mAge
'End Property
'Public Property Let Age(value As Integer)
' If value >= 0 And value <= 150 Then
' mAge = value
' Else
' Err.Raise 9999, "Person", "Age must be between 0 and 150"
' End If
'End Property
' Property (Email)
'Public Property Get Email() As String
' Email = mEmail
'End Property
'Public Property Let Email(value As String)
' mEmail = value
'End Property
' Methods
'Public Function Introduce() As String
' Introduce = "My name is " & mName & " and I am " & mAge & " years old."
'End Function
'Public Sub HaveBirthday()
' mAge = mAge + 1
'End Sub
' Class usage example in form
Private Sub ClassUsageExample()
' Create Person class instance
' Dim person As New Person
' Set properties
' person.Name = "John Doe"
' person.Age = 25
' person.Email = "[email protected]"
' Call methods
' Debug.Print person.Introduce()
' person.HaveBirthday()
' Debug.Print "Age after birthday: " & person.Age
Debug.Print "Class example (commented out)"
End Sub
' Form control operations
Private Sub FormControlExamples()
' Text box operations
Text1.Text = "Hello, Visual Basic!"
Text1.ForeColor = vbRed
Text1.BackColor = vbYellow
Text1.Font.Size = 12
Text1.Font.Bold = True
' Label operations
Label1.Caption = "Current time: " & Format(Now, "yyyy/mm/dd hh:nn:ss")
Label1.ForeColor = vbBlue
' Command button operations
Command1.Caption = "Click me"
Command1.Enabled = True
' List box operations
List1.Clear
List1.AddItem "Item 1"
List1.AddItem "Item 2"
List1.AddItem "Item 3"
List1.ListIndex = 0 ' Select first item
' Combo box operations
Combo1.Clear
Combo1.AddItem "Option A"
Combo1.AddItem "Option B"
Combo1.AddItem "Option C"
Combo1.Text = "Please select"
' Check box
Check1.Caption = "I agree"
Check1.Value = vbChecked
' Option buttons
Option1.Caption = "Male"
Option2.Caption = "Female"
Option1.Value = True
' Picture box
Picture1.BackColor = vbCyan
Picture1.BorderStyle = 1 ' With border
' Frame
Frame1.Caption = "Options"
End Sub
' Event procedure examples
Private Sub Command1_Click()
MsgBox "Button was clicked!", vbInformation, "Event"
End Sub
Private Sub Text1_Change()
' Processing when text is changed
Label2.Caption = "Character count: " & Len(Text1.Text)
End Sub
Private Sub List1_Click()
' Processing when list box item is clicked
If List1.ListIndex >= 0 Then
Text2.Text = "Selected item: " & List1.List(List1.ListIndex)
End If
End Sub
Private Sub Form_Load()
' Processing when form is loaded
Me.Caption = "Visual Basic Sample"
Me.BackColor = vbButtonFace
' Initialization
FormControlExamples
End Sub
Private Sub Form_Resize()
' Processing when form size is changed
If Me.WindowState <> vbMinimized Then
' Control size adjustment, etc.
Text1.Width = Me.ScaleWidth - 200
End If
End Sub
' Menu event examples
Private Sub mnuFileOpen_Click()
' File→Open menu processing
CommonDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
CommonDialog1.ShowOpen
If CommonDialog1.filename <> "" Then
' File opening processing
Text1.Text = ""
Open CommonDialog1.filename For Input As #1
Do Until EOF(1)
Text1.Text = Text1.Text & Input(1, 1)
Loop
Close #1
End If
End Sub
Private Sub mnuFileSave_Click()
' File→Save menu processing
CommonDialog1.Filter = "Text Files (*.txt)|*.txt"
CommonDialog1.ShowSave
If CommonDialog1.filename <> "" Then
' File saving processing
Open CommonDialog1.filename For Output As #1
Print #1, Text1.Text
Close #1
MsgBox "File saved", vbInformation
End If
End Sub
Database Operations and File Processing
' File operation examples
Private Sub FileOperations()
Dim filename As String
Dim fileContent As String
Dim lineContent As String
filename = "C:\temp\sample.txt"
' Write to file
Open filename For Output As #1
Print #1, "Visual Basic text file"
Print #1, "Second line content"
Print #1, "Third line content"
Print #1, "Current time: " & Now()
Close #1
Debug.Print "File created: " & filename
' Read from file (all at once)
Open filename For Input As #1
fileContent = ""
Do Until EOF(1)
Line Input #1, lineContent
fileContent = fileContent & lineContent & vbCrLf
Loop
Close #1
Debug.Print "=== File Content ==="
Debug.Print fileContent
' Read from file (line by line)
Open filename For Input As #1
Dim lineNumber As Integer
lineNumber = 1
Do Until EOF(1)
Line Input #1, lineContent
Debug.Print "Line" & lineNumber & ": " & lineContent
lineNumber = lineNumber + 1
Loop
Close #1
' Binary file operation example
Dim binaryFile As String
Dim byteData As Byte
binaryFile = "C:\temp\binary.dat"
' Binary write
Open binaryFile For Binary As #1
For i = 1 To 10
Put #1, , CByte(i * 10)
Next i
Close #1
' Binary read
Open binaryFile For Binary As #1
Debug.Print "=== Binary Data ==="
For i = 1 To LOF(1)
Get #1, i, byteData
Debug.Print "Position" & i & ": " & byteData
Next i
Close #1
End Sub
' INI file operations
Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" _
(ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, _
ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" _
(ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, _
ByVal lpFileName As String) As Long
Private Sub INIFileOperations()
Dim iniFile As String
Dim buffer As String
Dim result As Long
iniFile = App.Path & "\config.ini"
' Write to INI file
result = WritePrivateProfileString("Settings", "UserName", "John Doe", iniFile)
result = WritePrivateProfileString("Settings", "Language", "English", iniFile)
result = WritePrivateProfileString("Database", "Server", "localhost", iniFile)
result = WritePrivateProfileString("Database", "Port", "3306", iniFile)
Debug.Print "INI file created: " & iniFile
' Read from INI file
buffer = Space(255)
result = GetPrivateProfileString("Settings", "UserName", "", buffer, 255, iniFile)
Debug.Print "User name: " & Left(buffer, result)
buffer = Space(255)
result = GetPrivateProfileString("Settings", "Language", "", buffer, 255, iniFile)
Debug.Print "Language: " & Left(buffer, result)
buffer = Space(255)
result = GetPrivateProfileString("Database", "Server", "", buffer, 255, iniFile)
Debug.Print "Server: " & Left(buffer, result)
End Sub
' CSV file operations
Private Sub CSVOperations()
Dim csvFile As String
Dim csvLine As String
Dim fields() As String
Dim i As Integer
csvFile = "C:\temp\data.csv"
' Write to CSV file
Open csvFile For Output As #1
Print #1, "Name,Age,Department,Salary"
Print #1, "John Doe,25,Sales,300000"
Print #1, "Jane Smith,30,Development,400000"
Print #1, "Bob Johnson,35,Management,350000"
Close #1
Debug.Print "CSV file created: " & csvFile
' Read from CSV file
Open csvFile For Input As #1
' Read header row
Line Input #1, csvLine
Debug.Print "=== Header ==="
Debug.Print csvLine
Debug.Print "=== Data ==="
Do Until EOF(1)
Line Input #1, csvLine
fields = Split(csvLine, ",")
Debug.Print "Name: " & fields(0)
Debug.Print "Age: " & fields(1)
Debug.Print "Department: " & fields(2)
Debug.Print "Salary: " & Format(fields(3), "#,##0")
Debug.Print "---"
Loop
Close #1
End Sub
' Registry operations
Private Sub RegistryOperations()
Dim keyPath As String
Dim value As String
keyPath = "HKEY_CURRENT_USER\Software\MyApp"
' Save values to registry
SaveSetting "MyApp", "Settings", "UserName", "John Doe"
SaveSetting "MyApp", "Settings", "LastLogin", CStr(Now())
SaveSetting "MyApp", "Window", "Width", "800"
SaveSetting "MyApp", "Window", "Height", "600"
Debug.Print "Settings saved to registry"
' Read values from registry
value = GetSetting("MyApp", "Settings", "UserName", "")
Debug.Print "User name: " & value
value = GetSetting("MyApp", "Settings", "LastLogin", "")
Debug.Print "Last login: " & value
value = GetSetting("MyApp", "Window", "Width", "640")
Debug.Print "Window width: " & value
value = GetSetting("MyApp", "Window", "Height", "480")
Debug.Print "Window height: " & value
' Delete settings from registry
' DeleteSetting "MyApp", "Settings", "UserName"
' DeleteSetting "MyApp" ' Delete entire application settings
End Sub
' Simple database operations (DAO/ADO)
Private Sub DatabaseOperations()
' This example uses Access database
' Actual implementation requires reference settings:
' Microsoft DAO 3.6 Object Library or
' Microsoft ActiveX Data Objects Library
Debug.Print "Database operation example (requires reference settings for implementation)"
' DAO example (commented out)
'Dim db As Database
'Dim rs As Recordset
'Dim sql As String
' Open database
'Set db = OpenDatabase("C:\temp\sample.mdb")
' Execute SELECT query
'sql = "SELECT * FROM Users"
'Set rs = db.OpenRecordset(sql)
' Read records
'Do Until rs.EOF
' Debug.Print rs!UserName & ", " & rs!Age
' rs.MoveNext
'Loop
' Release resources
'rs.Close
'db.Close
'Set rs = Nothing
'Set db = Nothing
End Sub
Advantages and Disadvantages
Advantages
- Visual Development Environment: Easy GUI creation with drag-and-drop
- Easy-to-learn Syntax: BASIC language base, understandable for beginners
- Rich Controls: Abundant Windows standard UI components
- RAD (Rapid Application Development): Quick development from prototype to practical applications
- Event-driven Programming: Intuitive programming model
- Windows Compatibility: Easy integration with Windows API and various components
Disadvantages
- Legacy Technology: Decreasing adoption for new development
- Platform Limitation: Dependent on Windows platform
- Performance: Execution speed inferior to other languages even when compiled
- Lack of Modern Features: Limited object-oriented capabilities
- Future Concerns: Microsoft's end of support and recommendation to migrate to VB.NET
- Memory Management: Manual resource management required in some scenarios
Reference Links
Official Documentation
- Visual Basic 6.0 Documentation - Microsoft official documentation
- VB.NET Documentation - VB.NET migration information
Learning Resources
- Planet Source Code VB6 - Code sample collection
- VB Helper - Tutorials and samples
- VBForums - Community forums
Development Tools & Environment
- Visual Basic 6.0 - Development environment (archived)
- VB.NET - Successor Visual Studio
- VBA - VBA for Office
Migration & Alternative Technologies
- VB.NET Migration Guide - VB.NET migration guide
- C# for VB Developers - Migration information to C#