Published on 2025-12-08T00:25:39+08:00
VBA基础:你的第一个Excel程序
VBA基础:你的第一个Excel程序
什么是VBA?
Visual Basic for Applications (VBA) 是Excel内置的编程语言,用于高级自动化。
打开VBA编辑器
- 按Alt+F11
- 或开发工具 > Visual Basic
你的第一个宏
Sub HelloWorld()
MsgBox "你好,世界!"
End Sub
变量
Dim name As String
Dim age As Integer
Dim price As Double
Dim isActive As Boolean
name = "张三"
age = 25
操作单元格
' 使用Range
Range("A1").Value = "你好"
' 使用Cells(行, 列)
Cells(1, 1).Value = "你好"
' 读取值
Dim x As Variant
x = Range("A1").Value
循环
' For循环
For i = 1 To 10
Cells(i, 1).Value = i
Next i
' For Each循环
For Each cell In Range("A1:A10")
cell.Value = cell.Value * 2
Next cell
条件语句
If Range("A1").Value > 100 Then
MsgBox "高"
ElseIf Range("A1").Value > 50 Then
MsgBox "中"
Else
MsgBox "低"
End If
总结
这些VBA基础是构建强大Excel自动化解决方案的根基。