Excel 宏 VBA 自动化办公
FreeGuideOnline
16阅读
2026-07-10
vba Sub 过程名称() ' 在这里写代码 End Sub
- `Sub` 表示过程开始,`End Sub` 表示过程结束。
- 单引号 `'` 后面的内容为注释,不会被执行。
你可以在模块中编写多个 Sub 过程,通过宏对话框或按钮分别调用。
VBA 核心基础:变量、条件与循环
想从“录制使用者”进阶为“编写者”,必须掌握三个核心概念。
变量:临时存储数据
变量就像贴了标签的盒子,可以存放不同类型的数据。
Dim sales As Double ' 声明一个小数变量
Dim product As String ' 声明一个文本变量
sales = 1250.5
product = "笔记本电脑"
</code></pre>
<p>常用数据类型:<code>Integer</code>(整数)、<code>Long</code>(长整数)、<code>Double</code>(小数)、<code>String</code>(文本)、<code>Boolean</code>(真假)、<code>Date</code>(日期)。</p>
<h3 id="heading">条件判断:让程序做选择</h3>
<pre><code class="language-vba">If sales > 1000 Then
MsgBox "销售额达标"
Else
MsgBox "需要加油"
End If
</code></pre>
<ul>
<li><code>MsgBox</code> 会弹出一个信息提示框。</li>
<li>还可使用 <code>ElseIf</code> 进行多条件判断。</li>
</ul>
<h3 id="heading-1">循环:重复执行操作</h3>
<pre><code class="language-vba">Dim i As Integer
For i = 1 To 10
Cells(i, 1).Value = i ' 向 A1 到 A10 填入数字 1 到 10
Next i
</code></pre>
<p><code>Cells(行号, 列号)</code> 是最常用的单元格引用方式,如 <code>Cells(2,3)</code> 就是 C2 单元格。<code>For...Next</code> 循环会按指定次数重复执行中间代码。</p>
<h2 id="-excel-">操控 Excel 对象:单元格、工作表与工作簿</h2>
<p>VBA 本质上是自动化操作 Excel 的各种“对象”,理解三大家伙是核心。</p>
<h3 id="heading-2">单元格区域操作</h3>
<pre><code class="language-vba">' 写入值
Range("B2").Value = "产品A"
' 读取值到变量
Dim price As Double
price = Cells(2, 3).Value
' 设置背景色
Range("A1:C1").Interior.Color = RGB(255, 255, 0)
' 复制粘贴
Sheets("Sheet1").Range("A1:A10").Copy Destination:=Sheets("Sheet2").Range("A1")
</code></pre>
<ul>
<li><code>Range</code> 既可以用地址字符串,也可以使用 <code>Cells</code> 组合。</li>
<li><code>.Value</code> 是单元格最核心的属性,不要忘记带上它。</li>
</ul>
<h3 id="heading-3">工作表操作</h3>
<pre><code class="language-vba">' 添加新工作表
Sheets.Add After:=Sheets(Sheets.Count)
' 激活指定工作表
Sheets("数据源").Activate
' 循环所有工作表
Dim sh As Worksheet
For Each sh In ThisWorkbook.Sheets
Debug.Print sh.Name ' 在立即窗口打印工作表名
Next sh
</code></pre>
<p><code>ThisWorkbook</code> 代表包含此代码的那个工作簿。</p>
<h3 id="heading-4">工作簿操作</h3>
<pre><code class="language-vba">' 打开其他工作簿
Workbooks.Open "C:\报表\原始数据.xlsx"
' 保存并关闭
ActiveWorkbook.Close SaveChanges:=True
</code></pre>
<p>通常建议用 <code>ActiveWorkbook</code> 代表当前活动工作簿。</p>
<h2 id="heading-5">实用实例:从零构建自动化报表处理</h2>
<p>下面将前面知识串联成一个真实场景:<br/>
<strong>需求</strong>——在一个销售数据表中,自动计算每行总价,并标注高额订单,最后新建汇总表。</p>
<p>原始数据(Sheet1):</p>
<table>
<thead>
<tr>
<th>A:产品</th>
<th>B:数量</th>
<th>C:单价</th>
<th>D:总价</th>
<th>E:高额标记</th>
</tr>
</thead>
<tbody>
<tr>
<td>电脑</td>
<td>5</td>
<td>3500</td>
<td></td>
<td></td>
</tr>
<tr>
<td>手机</td>
<td>20</td>
<td>2000</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<h3 id="heading-6">编写自动化宏</h3>
<ol>
<li>按 <code>Alt+F11</code>,插入模块,编写如下代码:</li>
</ol>
<pre><code class="language-vba">Sub 生成销售汇总()
Dim lastRow As Long
Dim i As Long
Dim totalPrice As Double
Dim wsSource As Worksheet
Dim wsSummary As Worksheet
' 设置源工作表
Set wsSource = ThisWorkbook.Sheets("Sheet1")
' 找到最后一行数据
lastRow = wsSource.Cells(wsSource.Rows.Count, 1).End(xlUp).Row
' 循环每一行数据,计算总价并标记高额
For i = 2 To lastRow
totalPrice = wsSource.Cells(i, 2).Value * wsSource.Cells(i, 3).Value
wsSource.Cells(i, 4).Value = totalPrice
If totalPrice > 20000 Then
wsSource.Cells(i, 5).Value = "高额"
wsSource.Cells(i, 5).Font.Color = RGB(255, 0, 0)
End If
Next i
' 新建汇总表
Set wsSummary = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
wsSummary.Name = "汇总"
' 写入汇总标题
wsSummary.Range("A1").Value = "汇总信息"
wsSummary.Range("A2").Value = "总订单数"
wsSummary.Range("B2").Value = lastRow - 1
wsSummary.Range("A3").Value = "总金额"
wsSummary.Range("B3").Value = Application.WorksheetFunction.Sum(wsSource.Range("D2:D" & lastRow))
MsgBox "报表生成完毕!"
End Sub
</code></pre>
<ol>
<li>关闭编辑器,在 Excel 中按 <code>Alt+F8</code>,运行 <code>生成销售汇总</code>。效果立现。</li>
</ol>
<h3 id="heading-7">代码要点解析</h3>
<ul>
<li><code>lastRow</code> 动态找到数据最后一行,避免硬编码行号,让宏具备通用性。</li>
<li><code>Application.WorksheetFunction.Sum</code> 调用 Excel 内置工作表函数,与直接写公式效果相同。</li>
<li><code>Set</code> 关键字用于给对象变量(如工作表)赋值。</li>
<li>在循环中处理单个订单,条件判断后设置字体颜色,完成批量标记。</li>
</ul>
<h2 id="heading-8">让宏更智能:错误处理与用户交互</h2>
<p>实际工作环境总有意外,比如源表不存在或数据缺失,你的宏应该具备防错能力。</p>
<h3 id="heading-9">基础错误处理</h3>
<pre><code class="language-vba">On Error GoTo 错误处理
' 正常代码
Sheets("不存在的表").Activate ' 这行会报错
Exit Sub ' 如果没有错误,在此退出过程
错误处理:
MsgBox "工作表不存在,请检查。错误描述:" & Err.Description
</code></pre>
<p><code>On Error GoTo 标签</code> 让程序遇到错误时跳转到指定位置,避免直接崩溃。</p>
<h3 id="inputbox--msgbox">与用户交互:InputBox 和 MsgBox</h3>
<pre><code class="language-vba">Dim 阈值 As Double
阈值 = InputBox("请输入高额订单的判断金额")
If 阈值 = 0 Then Exit Sub ' 用户取消或输入0则退出
MsgBox "已设定阈值为:" & 阈值 & " 元", vbInformation, "提示"</code></pre>