我正在Excel中編寫VBA腳本以基於某些表格將文本輸出到Word文檔。大多數情況下,一切都很美妙(我在教我自己,因爲我有很多來自stackoverflow的幫助)。我有一個相當長的代碼,所以在這裏複製它會很困難,我會試着展示相關的部分。VBA寫入Word,更改字體格式
我遇到的問題是在我嘗試更改字體的格式時。 我已經創建了一些不同的風格,以協助標準化的格式選項,
With wrdDoc
.Styles.Add ("SectionHeader")
.Styles.Add ("NoFormat")
.Styles.Add ("Marginal")
.Styles.Add ("Failed")
.Styles.Add ("Unknown")
.Styles.Add ("Bold")
With .Styles("SectionHeader")
.Font.Name = "Calibri"
.Font.Size = 12
.Font.Underline = True
.Font.Bold = False
.Font.Italic = False
.Font.Strikethrough = False
.Font.Subscript = False
.Font.Superscript = False
.Font.Color = RGB(0, 0, 0)
End With
With .Styles("NoFormat")
.Font.Name = "Calibri"
.Font.Size = 12
.Font.Underline = False
.Font.Bold = False
.Font.Italic = False
.Font.Strikethrough = False
.Font.Subscript = False
.Font.Superscript = False
.Font.Color = RGB(0, 0, 0)
End With
With .Styles("Marginal")
.Font.Name = "Calibri"
.Font.Size = 12
.Font.Underline = False
.Font.Bold = True
.Font.Italic = False
.Font.Strikethrough = False
.Font.Subscript = False
.Font.Superscript = False
.Font.Color = RGB(0, 0, 255)
End With
With .Styles("Failed")
.Font.Name = "Calibri"
.Font.Size = 12
.Font.Underline = True
.Font.Bold = True
.Font.Italic = False
.Font.Strikethrough = False
.Font.Subscript = False
.Font.Superscript = False
.Font.Color = RGB(255, 0, 0)
End With
With .Styles("Unknown")
.Font.Name = "Calibri"
.Font.Size = 12
.Font.Underline = False
.Font.Bold = True
.Font.Italic = False
.Font.Strikethrough = False
.Font.Subscript = False
.Font.Superscript = False
.Font.Color = RGB(0, 176, 80)
End With
With .Styles("Bold")
.Font.Name = "Calibri"
.Font.Size = 12
.Font.Underline = False
.Font.Bold = True
.Font.Italic = False
.Font.Strikethrough = False
.Font.Subscript = False
.Font.Superscript = False
.Font.Color = RGB(0, 0, 0)
End With
End With
於是,我試圖做到這一點,在輸出文本中的句子變化的中間有一個字格式,
With wrdApp.Selection
.Style = wrdDoc.Styles("NoFormat")
.TypeText Text:="The start of this sentence is "
.Style = wrdDoc.Styles("Unknown")
.TypeText Text:="unknown"
.Style = wrdDoc.Styles("NoFormat")
.TypeText Text:=" so we will keep trying..."
.TypeParagraph
End With
但我得到的是沒有改變的句子,如果該單詞的格式。
更奇怪的是,我也有應適用我的「大膽」的風格發揮到了整個句子的幾個組成部分,其中之一不適用大膽,而另一個沒有,
With wrdApp.Selection
.Style = wrdDoc.Styles("Bold")
.TypeText Text:="This one doesn't work"
End With
With wrdApp.Selection
.Style = wrdDoc.Styles("Bold")
.TypeText Text:="this one works!"
.TypeParagraph
End With
我會也喜歡能夠應用
.ParagraphFormat.SpaceAfter = 0
.ParagraphFormat.SpaceBefore = 0
對這些選擇的一些,但我想不出如何做到這一點。我可以將它用於文檔的「範圍」,但最終會將其應用於文檔的現有部分,但不會應用於任何新文本。
我應該補充一點,如果我明確指出了將代碼「輸入」到Word中的格式更改,它可以很好地工作,它只是嘗試使用「樣式」。這導致了更多的代碼行。 – tincanfury 2014-10-09 13:37:32