Today's Goals
- Understand variables
- Know the common data types
- Declare and use variables
- Understand scope
Key Concepts
1. Declaring Variables
A variable is a name for a value you can read and change while the code runs. VBA declares variables with Dim:
vbaDim variableName As DataTypeNames start with a letter (Chinese characters work too) and take no spaces, periods, or reserved words. Option Explicit at the top of a module forces declaration before use — keep it on.
2. Common Data Types
| Data Type | Description | Example |
|---|---|---|
| Integer | Whole numbers (-32,768 to 32,767) | Dim i As Integer |
| Long | Long integer (about ±2.1 billion) | Dim l As Long |
| String | Text | Dim s As String |
| Double | Double-precision floating point | Dim d As Double |
| Boolean | True / False | Dim b As Boolean |
| Date | Dates and times | Dim dt As Date |
Rules of thumb: Long for whole numbers, Double for money and decimals; date literals go between hash marks, e.g. #1999-1-1#. An untyped variable becomes a Variant — avoid that when you can.
3. Assignment, Concatenation, and Conversion
= assigns, & joins strings and numbers, vbCrLf breaks a line, and a trailing _ continues a statement. Cell and InputBox values arrive as text — convert before doing math: CInt, CDbl, CStr, Val.
4. Variable Scope
- Procedure-level:
Diminside a procedure — visible only there, gone when it ends - Module-level:
Dimat the top of a module — visible to that module's procedures - Global:
Publicat the top of a module — visible to the whole project
Use the smallest scope that works.
Today's Code
vbaSub 变量示例()
' Declare variables
Dim name As String
Dim age As Integer
Dim price As Double
Dim isStudent As Boolean
' Assign values
name = "张三"
age = 25
price = 99.5
isStudent = True
' Use them
MsgBox "姓名: " & name & vbCrLf & _
"年龄: " & age & vbCrLf & _
"价格: " & price
End SubReal-World Scenario
The setup: a sales rep quotes an order — unit price 199.9, three units at 20% off, payable amount exact to the cent.
vbaSub 计算订单金额()
Dim 单价 As Double, 数量 As Long, 折扣 As Double, 应付 As Double
单价 = 199.9
数量 = 3
折扣 = 0.8
应付 = 单价 * 数量 * 折扣
MsgBox "应付金额: " & Format(应付, "0.00") & " 元"
End SubResult: 199.9 × 3 × 0.8 = 479.76. Format(应付, "0.00") forces two decimal places so no floating-point tail shows, and a later price or discount change touches only the assignment lines — that is why variables beat hard-coded numbers.
Exercises
- Declare variables that store your name and age
- Write a program that adds two numbers
- Try variables of different data types
Exercise Solutions
- Declare with Dim —
Dim name As String, age As Integer— then assign each. - Declare two numeric variables, run
sum = a + b, and show the result with MsgBox. - Declare Integer, String, Boolean, and Date variables, assign values, and watch what each holds.
Extension Exercises
- Ask for a birth year with
InputBox, then calculate and show the age (Year(Date)gives the current year). - Swap two variables through a temporary variable.
Common Errors and Troubleshooting
| Error / Symptom | Cause | Fix |
|---|---|---|
Run-time error '13': Type mismatch |
Non-numeric text assigned to a numeric variable | Check the source; convert with Val/CInt |
Compile error: Variable not defined |
Undeclared or misspelled variable | Add a Dim; check the spelling |
| Two "numbers" concatenate instead of adding | The cell values are text | Convert with Val() before calculating |
Summary
Declare first, pick the right type, keep the scope tight — and convert cell data before doing math on it.
由在线工具箱(www.vba.net)整理制作