如何批量修改Word文件中的表格樣式和題注格式?
阿新 • • 發佈:2019-01-01
在進行大型專案的方案文件設計時,一個文件中有可能涉及到上百個圖表,在最後定稿的時候,需要進行統一的格式化處理。面對這些數目龐大的表格,挨個用格式刷進行處理,一路刷下來往往手都會刷酸,更令人奔潰的是好不容易刷完了,發現字型或大小不對,這時候可能需要再重新刷一遍。那麼如果能提高效率呢?
word中的VBA功能,就是專為這種工作量龐大,而需要重複的工作設計的。對錶格的樣式進行統一處理VBA程式碼如下:
Sub FormatAllTables()
For i = 1 To ActiveDocument.Tables.Count
' ActiveDocument.Tables(i).Style = "my"
With ActiveDocument.Tables(i).Range.ParagraphFormat
.LeftIndent = CentimetersToPoints(0)
.RightIndent = CentimetersToPoints(0)
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineSpacingRule = wdLineSpace1pt5
.Alignment = wdAlignParagraphJustify
.WidowControl = False
.KeepWithNext = False
.KeepTogether = False
.PageBreakBefore = False
.NoLineNumber = False
.Hyphenation = True
.FirstLineIndent = CentimetersToPoints(0)
.OutlineLevel = wdOutlineLevelBodyText
.CharacterUnitLeftIndent = 0
.CharacterUnitRightIndent = 0
.CharacterUnitFirstLineIndent = 0
.LineUnitBefore = 0
.LineUnitAfter = 0
.MirrorIndents = False
.TextboxTightWrap = wdTightNone
.AutoAdjustRightIndent = True
.DisableLineHeightGrid = False
.FarEastLineBreakControl = True
.WordWrap = True
.HangingPunctuation = True
.HalfWidthPunctuationOnTopOfLine = False
.AddSpaceBetweenFarEastAndAlpha = True
.AddSpaceBetweenFarEastAndDigit = True
.BaseLineAlignment = wdBaselineAlignAuto
End With
' 設定表中的字型及大小
ActiveDocument.Tables(i).Select
With Selection
.Font.Size = 12
.Font.Name = "宋體"
End With
ActiveDocument.Tables(i).Cell(1, 1).Select
With Selection
.SelectRow
.Font.Bold = True
.Shading.BackgroundPatternColor = -603923969
.ParagraphFormat.Alignment = wdAlignParagraphCenter
End With
Next
End Sub
在文件編寫中,表格中題注的字型及大小一般與正文也不一樣,需要單獨進行設定,由於題注設定需要自動編號,可通過VBA程式碼對這些自動編號的題注進行自動化處理,其基本思路是查詢帶有域“圖”的所有文字;選中它,然後格式貼上。其程式碼如下:
Sub FormatTableTitle()
myHeadings = ActiveDocument.GetCrossReferenceItems("圖")
findTxt = ""
For i = 1 To UBound(myHeadings)
'MsgBox myHeadings(i)
findTxt = myHeadings(i)
With Selection.Find
.Text = findTxt
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = True
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.PasteFormat
Next i
End Sub