我正在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