标签归档:vba

用vba批量调整word文件的字体

其实是年前遇到的破事,现在终于有时间记录一下是怎么解决的了。

遇到的问题:一大堆的.docx文件用了莫名其妙的中文字体,造成所有中文字都挤在一起,根本没法看。

处理方法:设定文件字体为宋体,并且将字体嵌入到文件中。顺便调整一下章节前后的空白。

由于文件数量比较多,实在是懒得一个一个去手工处理,于是想起了很多年前玩过的“宏/macro”。以下是代码,如果有需要随意拿走用。这段宏代码会处理目录下所有的文件,将正文、页眉页脚字体都设置为宋体,并且去掉段落前后的空白。

Sub Macro1()
 Dim vDirectory As String
    Dim oDoc As Document
    vDirectory = "C:\some_dir\"
    vFile = Dir(vDirectory & "*.*", vbNormal)
Do While vFile <> ""
Set oDoc = Documents.Open(FileName:=vDirectory & vFile)

ActiveDocument.SetCompatibilityMode (wdWord2010)
ActiveDocument.BuiltInDocumentProperties("Author") = "liukang"

ActiveDocument.Range.Font.Name = "宋体"
With ActiveDocument.Sections(1)
.Footers(wdHeaderFooterPrimary).Range.Font.Name = "宋体"
.Headers(wdHeaderFooterPrimary).Range.Font.Name = "宋体"
.Footers(wdHeaderFooterFirstPage).Range.Font.Name = "宋体"
.Headers(wdHeaderFooterFirstPage).Range.Font.Name = "宋体"
End With
With ActiveDocument.Sections(1).Range.ParagraphFormat
        .SpaceBeforeAuto = False
        .SpaceAfterAuto = False
        .WordWrap = True
End With
    
    ActiveDocument.EmbedTrueTypeFonts = True
    ActiveDocument.SaveSubsetFonts = True
    ActiveDocument.DoNotEmbedSystemFonts = False
    ActiveDocument.Save
    ActiveDocument.Close
    vFile = Dir
Loop
End Sub