我正在 Excel 中编写 VBA 脚本,以将基于某些表格的文本输出到 Word 文档。在大多数情况下,一切都很顺利(我在 stackoverflow 的帮助下自学)。我有一个相当长的代码,因此将其全部复制到这里会很困难,我将尝试展示相关部分。
我遇到的问题是在尝试更改字体格式时遇到的问题。
我创建了一些不同的样式来帮助标准化格式选项,
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
但我得到的是没有改变该单词的 if 格式的句子。
更奇怪的是,我还有一些组件应该将我的“粗体”样式应用于整个句子,其中一个组件确实应用了粗体,另一个则没有,
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
其中一些选择,但我不知道该怎么做。我可以让它对文档的“范围”执行此操作,但最终会将其应用于文档的现有部分,而不是任何新文本。