在 Microsoft Word 中使用 VBA(Visual Basic for Applications)宏可以极大地提高文档处理效率。以下是一些实用且常见的宏代码示例,适用于日常办公场景。
1. 插入当前日期和时间
Sub InsertDateTime()
Selection.InsertBefore Text:=Format(Now(), "yyyy年mm月dd日 hh:nn:ss")
End Sub
2. 批量删除空段落
Sub DeleteEmptyParagraphs()
Dim para As Paragraph
For Each para In ActiveDocument.Paragraphs
If Len(Trim(para.Range.Text)) = 1 Then ' 段落标记占1字符
para.Range.Delete
End If
Next para
End Sub
3. 全文统一字体和字号
Sub SetFontAll()
With ActiveDocument.Content.Font
.Name = "宋体"
.Size = 12
End With
End Sub
4. 自动保存文档
Sub AutoSaveDocument()
If ActiveDocument.Saved = False Then
ActiveDocument.Save
End If
End Sub
5. 查找并高亮关键词
Sub HighlightKeyword()
Dim keyword As String
keyword = "重要"
With ActiveDocument.Content.Find
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = True
.Text = keyword
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = True
.Execute Replace:=wdReplaceAll
End With
End Sub
提示:使用宏前请确保已启用“开发工具”选项卡,并将宏安全性设置为“启用所有宏”(仅限可信环境)。