Standardizing Microsoft Word Documents with VBA
To ensure consistent formatting in formal reports, you can utilize VBA macros to automate font styles, paragraph spacing, and page numbering. The following script standardizes document layout by iterating through paragraphs and applying specific styling rules:
Sub FormatOfficialDocument()
Dim doc As Document
Set doc = ActiveDocument
' Page Setup
With doc.PageSetup
.TopMargin = MillimetersToPoints(25)
.BottomMargin = MillimetersToPoints(25)
.LeftMargin = MillimetersToPoints(28)
.RightMargin = MillimetersToPoints(28)
End With
' Iterate and Apply Styles
Dim para As Paragraph
For Each para In doc.Paragraphs
With para.Range
If para.Style = wdStyleHeading1 Then
.Font.Name = "SimHei"
.Font.Size = 16
Else
.Font.Name = "FangSong"
.Font.Size = 16
.ParagraphFormat.LineSpacingRule = wdLineSpaceExactly
.ParagraphFormat.LineSpacing = 28
End If
End With
Next para
End Sub
Formating PowerPoint Presentations
Consistency in presentations requires traversing through slides, shapes, and nested tables to enforce a unified typeface and line spacing, ensuring that even grouped elements are correctly updated:
Sub StandardizeSlideFonts()
Dim sld As Slide, shp As Shape
For Each sld In ActivePresentation.Slides
For Each shp In sld.Shapes
' Handle standard text boxes
If shp.HasTextFrame Then
FormatTextRange shp.TextFrame.TextRange
End If
' Handle grouped shapes
If shp.Type = msoGroup Then
Dim subShp As Shape
For Each subShp In shp.GroupItems
If subShp.HasTextFrame Then FormatTextRange subShp.TextFrame.TextRange
Next
End If
Next
Next
End Sub
Sub FormatTextRange(tr As TextRange)
tr.Font.Name = "Microsoft YaHei"
tr.ParagraphFormat.SpaceWithin = 1.5
End Sub
Programmatic Document Manipulation with Python-docx
For more complex document processing, the python-docx library allows for deep XML manipulation, wich is necessary when handling specific Chinese font settings or complex table borders that are not easily exposed by the high-level API.
When setting East Asian fonts, you must target the underlying OpenXML property rather than the standard font.name attribute:
from docx.oxml.ns import qn
from docx.table import _Cell
from docx.oxml import OxmlElement
def apply_east_asian_font(run, font_name):
rPr = run._element.get_or_add_rPr()
east_asia = OxmlElement('w:eastAsia')
east_asia.set(qn('w:val'), font_name)
rPr.append(east_asia)
def style_table_borders(cell: _Cell):
tcPr = cell._tc.get_or_add_tcPr()
borders = OxmlElement('w:tcBorders')
for border_type in ['top', 'left', 'bottom', 'right']:
edge = OxmlElement(f'w:{border_type}')
edge.set(qn('w:val'), 'single')
edge.set(qn('w:sz'), '4')
borders.append(edge)
tcPr.append(borders)
Formal Document Hierarchical Indexing
Maintaining proper hierarchy is critical for professional documentation. Follow these standard numbering conventions:
- Level 1: 一、 二、 三、
- Level 2: (一) (二) (三)
- Level 3: 1. 2. 3.
- Level 4: (1) (2) (3)
- Level 5: 1) 2) 3)