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:

vba
Dim variableName As DataType

Names 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: Dim inside a procedure — visible only there, gone when it ends
  • Module-level: Dim at the top of a module — visible to that module's procedures
  • Global: Public at the top of a module — visible to the whole project

Use the smallest scope that works.

Today's Code

vba
Sub 变量示例() ' 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 Sub

Real-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.

vba
Sub 计算订单金额() Dim 单价 As Double, 数量 As Long, 折扣 As Double, 应付 As Double 单价 = 199.9 数量 = 3 折扣 = 0.8 应付 = 单价 * 数量 * 折扣 MsgBox "应付金额: " & Format(应付, "0.00") & " 元" End Sub

Result: 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

  1. Declare variables that store your name and age
  2. Write a program that adds two numbers
  3. Try variables of different data types

Exercise Solutions

  1. Declare with Dim — Dim name As String, age As Integer — then assign each.
  2. Declare two numeric variables, run sum = a + b, and show the result with MsgBox.
  3. Declare Integer, String, Boolean, and Date variables, assign values, and watch what each holds.

Extension Exercises

  1. Ask for a birth year with InputBox, then calculate and show the age (Year(Date) gives the current year).
  2. 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)整理制作