Lesson 9: Variables and Constants in VB2019
Master data storage and management for robust application development
Key Takeaway
Variables and constants are essential for storing and managing data in your applications. Understanding their declaration, scope, and usage is fundamental to effective Visual Basic programming.
Variables are like mailboxes in the post office. The content of the variable changes every now and then, just like the mailboxes. In Visual Basic 2019, variables are specific areas allocated by computer memory to store data. Constants are different from variables in that their values do not change during program execution.
9.1 Variable Names
To name a variable in VB2019, you must follow these rules:
1 Character Limit
Must be less than 255 characters
2 No Spaces
Spaces are not allowed
3 Start with Letter
Cannot begin with a number
4 No Periods
Periods are not permitted
| Valid Names | Invalid Names |
|---|---|
| My_Name | My.Name (period not allowed) |
| vb2019 | 2019vb (cannot start with number) |
| Long_Name_Can_beUSE | LongName&Canbe&Use (ampersand not acceptable) |
9.2 Declaring Variables
In Visual Basic 2019, you need to declare variables before you can use them. Variables are usually declared in the general section of the code windows using the Dim statement.
Declaration Syntax
The syntax to declare a variable in VB2019 is:
Dim VariableName As DataType
For multiple variables:
Dim VariableName1 As DataType1 Dim VariableName2 As DataType2 Dim VariableName3 As DataType3
Or in a single line:
Dim VariableName1 As DataType1, VariableName2 As DataType2, VariableName3 As DataType3
Example 9.1: Simple Variable Declaration
This example declares two string variables and concatenates them using the ampersand sign &.
Private Sub BtnShow_Click(sender As Object, e As EventArgs) Handles BtnShow.Click ' Declare and initialize a string variable Dim YourName As String = " George" ' Declare a string variable and assign value later Dim MyMsg As String MyMsg = "Happy Birthday!" ' Display concatenated message MsgBox(MyMsg & YourName) End Sub
Output:
Example 9.2: Simple Calculator
In this example, we create a simple calculator that takes user input, performs addition, and displays the current date.
Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click ' Declare variables with different data types Dim YourName As String Dim Num1 As Integer Dim Num2 As Single Dim Sum As Integer Dim RunDate As Date ' Assign values from form controls YourName = TxtName.Text Num1 = Val(TxtNum1.Text) Num2 = Val(TxtNum2.Text) ' Perform calculation Sum = Num1 + Num2 ' Display results LblSum.Text = Str(Sum) ' Format and display date RunDate = Format(Now, "General Date") LblDate.Text = RunDate End Sub
9.3 Assigning Values to Variables
After declaring variables, we can assign values using the assignment operator (=). The syntax is:
Variable = Expression
You can also declare and initialize a variable in one line:
Dim VarName As String = "ABC" Dim VarNum As Integer = 100
Examples of valid assignments:
firstNumber = 100 secondNumber = firstNumber - 99 userName = "John Lyan" Label1.Visible = True Command1.Visible = False Label4.text = textbox1.Text ThirdNumber = Val(usernum1.Text) total = firstNumber + secondNumber + ThirdNumber
Example 9.3: Type Mismatch Error
An error occurs when you try to assign a value to a variable of an incompatible data type.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' Declare an integer variable Dim YourMessage As Integer ' Attempt to assign a string to an integer variable YourMessage = "Happy Birthday!" MsgBox(YourMessage) End Sub
Output:
Best Practice
Always declare variables with the appropriate data type for the values they will hold. Use Option Strict On to enforce type safety and prevent implicit conversions that might cause runtime errors.
9.4 Scope of Declaration
The scope of a variable determines where it can be accessed in your program. Visual Basic 2019 provides different keywords to control variable scope.
Dim Keyword
Declares a local variable accessible only within the current procedure or block.
Dim localVar As Integer = 10
Static Keyword
Preserves the value of a local variable between procedure calls.
Static counter As Integer = 0
Public Keyword
Declares a global variable accessible by all procedures and modules.
Public globalVar As String = "Hello"
Scope Comparison
| Keyword | Scope | Lifetime | Example |
|---|---|---|---|
| Dim | Local to procedure or block | While procedure is executing | Dim x As Integer |
| Static | Local to procedure | Entire program execution | Static count As Integer |
| Public | Entire application | Entire program execution | Public appName As String |
9.5 Declaring Constants
Constants are different from variables in that their values do not change during program execution. The syntax to declare a constant is:
Const ConstantName As DataType = Value
Important Notes
Constants must be initialized when declared and cannot be changed later. Use constants for values that are fixed and used multiple times in your program, such as mathematical constants, configuration values, or fixed strings.
Example 9.4: Using Constants
This example calculates the area of a circle using the constant Pi.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ' Declare a constant for Pi Const Pi As Single = 3.142 ' Declare and initialize radius Dim R As Single = 10 ' Calculate area of circle Dim AreaCircle As Single AreaCircle = Pi * R ^ 2 ' Display result MsgBox("Area of circle with radius " & R & " = " & AreaCircle) End Sub
Output:
Lesson Summary
In this lesson, you've learned how to work with variables and constants in Visual Basic 2019:
Variable Naming
Understand the rules for naming variables in VB2019
Declaration
Use Dim to declare variables with appropriate data types
Assignment
Assign values to variables and avoid type mismatch errors
Scope
Control variable scope with Dim, Static, and Public
Constants
Declare and use constants for fixed values
You've learned how to declare, assign, and manage variables and constants in Visual Basic 2019. These are fundamental concepts that you'll use in every program you create. In the next lesson, we'll explore how to work with arrays.
Next Lesson
Ready to learn about arrays? Continue to Lesson 10: Creating Arrays.
Related Resources
Visual Basic 2019 Made Easy
Unlock the power of Visual Basic 2019 with this comprehensive, easy-to-follow handbook written by Dr. Liew, renowned educator and founder of the popular programming tutorial website VBtutor.net. Whether you're new to programming or brushing up your skills, this book is your perfect companion to learn Visual Basic 2019 from the ground up.
What You'll Learn:
- Understand Core Programming Concepts: Grasp the foundational principles of Visual Basic 2019, including variables, data types, conditional logic, loops, and event-driven programming.
- Develop Real Windows Desktop Applications: Build fully functional and interactive Windows apps using Visual Studio 2019—guided through step-by-step tutorials.
- Apply Dozens of Ready-to-Use Examples: Explore a rich collection of practical sample programs, from basic calculators to image viewers and database applications.
- Adapt and Reuse Code for Your Own Projects: Customize professionally written code snippets to speed up your development process and bring your ideas to life.
- Package and Deploy Like a Pro: Learn how to compile, test, and distribute your Visual Basic applications seamlessly with built-in deployment tools.
Visual Basic Programming With Code Examples
Visual Basic Programming with Code Examples offers a unique dual-format approach, showcasing sample codes in both Visual Basic 6 (VB6) and VB.NET. This side-by-side presentation helps you understand the evolution of Visual Basic and empowers you to work confidently across both environments.
What You'll Learn:
- Core Concepts Made Easy: Explore data types, control structures, file handling, procedures, user interface design, and more.
- Hands-On Application Building: Design real-world applications, including financial calculators, educational tools, games, multimedia apps, and database systems.
- 48 Practical Code Examples: Study and customize fully explained programs that illustrate key programming techniques.
- Dual-Code Format: Learn to translate and adapt code between VB6 and VB.NET seamlessly.