Declaring Variables and Writing Simple Programs in Visual Basic (VB6 /
VBA)
1. Introduction to Variables in Visual Basic
A variable is a storage location in the computer’s memory where values can be stored,
retrieved, and changed during program execution.
In Visual Basic, variables must be declared before they are used, so that the computer
knows:
- The name of the variable
- The type of data it will hold (e.g., number, text)
2. Declaring Variables using Dim
The keyword Dim (short for Dimension) is used to declare variables in Visual Basic.
Example:
Dim L As Single ' Length of the rectangle
Dim W As Single ' Width of the rectangle
Dim A As Single ' Area of the rectangle
Common Data Types:
- Integer → For whole numbers (e.g., 10, -3, 250)
- Single → For decimal numbers (e.g., 3.14, 45.6)
- String → For text (e.g., "Hello", "Kenya")
- Boolean → For True/False values
3. Assigning Values from a TextBox
In VB applications, users enter data into TextBoxes. To use the values for calculations, we
must convert the text into numbers.
L = Val(txtLength.Text) ' Convert text input to a number
W = Val(txtWidth.Text)
A=L*W ' Calculate the area
txtArea.Text = Str(A) ' Convert number to string and display in textbox
4. Full Code Example – Area of a Rectangle
Private Sub cmdCalculate_Click()
Dim L As Single, W As Single, A As Single
L = Val(txtLength.Text)
W = Val(txtWidth.Text)
A=L*W
txtArea.Text = Str(A)
End Sub
Private Sub cmdExit_Click()
' Exit from the program
End
End Sub
5. Control Naming Standards in Visual Basic
Control Prefix Example Name
Form frm frmEmployee
Label lbl lblStart
Command Button cmd cmdSave, cmdExit
Text Box txt txtLength, txtArea
List Box lst lstCountries
Picture Box pic picResult
6. Steps to Run the Program
1. Open Visual Basic and start a new project.
2. Place two TextBoxes (for Length and Width), and a third one (for Area).
3. Place two Labels (to show “Enter Length”, “Enter Width”).
4. Place two Command Buttons (Calculate and Exit).
5. Double-click on Calculate button and enter the above code.
6. Run the program → enter values → click Calculate → result is displayed.
7. Next Improvements
- Add Error Handling (check for empty or invalid input).
- Format the result to 2 decimal places.
- Add Perimeter Calculation as an extra feature.