透過 VBA 可精確控制 Word 文件的各類格式,以下提供六個實用範例,涵蓋選取範圍、指定區域、插入文字、切換段前間距、切換粗體、調整頁邊距等常見操作。
Sub FormatSelection()
With Selection.Font
.Name = "Times New Roman"
.Size = 14
.AllCaps = True
End With
With Selection.ParagraphFormat
.LeftIndent = InchesToPoints(0.5)
.Space1 ' 原碼片段,實際建議用 .SpaceAfter 或 .SpaceBefore
End With
End Sub
Sub FormatRange()
Dim rngFormat As Range
Set rngFormat = ActiveDocument.Range( _
Start:=ActiveDocument.Paragraphs(1).Range.Start, _
End:=ActiveDocument.Paragraphs(3).Range.End)
With rngFormat
.Font.Name = "Arial"
.ParagraphFormat.Alignment = wdAlignParagraphJustify
End With
End Sub
Sub InsertFormatText()
Dim rngFormat As Range
Set rngFormat = ActiveDocument.Range(Start:=0, End:=0)
With rngFormat
.InsertAfter Text:="Title"
.InsertParagraphAfter
With .Font
.Name = "Tahoma"
.Size = 24
.Bold = True
End With
End With
With ActiveDocument.Paragraphs(1)
.Alignment = wdAlignParagraphCenter
.SpaceAfter = InchesToPoints(0.5)
End With
End Sub
Sub ToggleParagraphSpace()
With Selection.Paragraphs(1)
If .SpaceBefore <> 0 Then
.SpaceBefore = 0
Else
.SpaceBefore = 6 ' 原碼為 6,對應 12 點需設 12
End If
End With
End Sub
Sub ToggleBold()
Selection.Font.Bold = wdToggle
End Sub
Sub FormatMargins()
With ActiveDocument.PageSetup
.LeftMargin = .LeftMargin + InchesToPoints(0.5)
.RightMargin = .RightMargin + InchesToPoints(0.5)
End With
End Sub
以上範例展示了 Selection、Range、Font、ParagraphFormat、PageSetup 等核心物件的操作方式,可直接套用或修改參數滿足實際需求。