我正在编写VBA脚本,以从已定义的模板生成Word文档。在其中,我需要能够为每个标题写一个标题以及一个正文。举一个小例子,我有一个Word文档,仅包含<PLACEHOLDER>
。对于我需要编写的每个标题和正文,我使用VBA中的“查找和替换”功能来找到<PLACEHOLDER>
,并将其替换为标题名称,换行符,然后再次使用<PLACEHOLDER>
。重复此操作,直到写入每个标题名称和正文,然后将最后的<PLACEHOLDER>
换行。
文本替换工作正常,但是我指定的样式被替换的 next 调用所覆盖。这导致我刚刚替换的所有东西都具有我对替换函数的 last 调用的样式。
VBA代码(运行main
)
Option Explicit
Sub replace_stuff(search_string As String,replace_string As String,style As Integer)
With activeDocument.Range.Find
.Text = search_string
.Replacement.Text = replace_string
.Replacement.style = style
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchWholeWord = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Sub
Sub main()
Dim section_names(2) As String
section_names(0) = "Introduction"
section_names(1) = "Background"
section_names(2) = "Conclusion"
Dim section_bodies(2) As String
section_bodies(0) = "This is the body text for the introduction! Fetched from some file."
section_bodies(1) = "And Background... I have no issue fetching data from the files."
section_bodies(2) = "And for the conclusion... But I want the styles to 'stick'!"
Dim i As Integer
For i = 0 To 2
' Writes each section name as wsStyleHeading2,and then the section body as wdStyleNormal
Call replace_stuff("<PLACEHOLDER>",section_names(i) & Chr(11) & "<PLACEHOLDER>",wdStyleHeading2)
Call replace_stuff("<PLACEHOLDER>",section_bodies(i) & Chr(11) & "<PLACEHOLDER>",wdStyleNormal)
Next i
Call replace_stuff("<PLACEHOLDER>",Chr(11),wdStyleNormal)
End Sub
输入文档:仅包含<PLACEHOLDER>
的Word文档。
<PLACEHOLDER>
预期输出: 我希望每个标题都将以我指定的样式显示,并且可以从导航窗格中进行如下查看:
实际输出:但是,我实际上得到的是像这样的wdStyleNormal
样式的所有东西:
我认为可以通过在每个样式转换之间插入一个换行符来解决问题,但是当我尝试使用vbCrLF
或Chr(10) & Chr(13)
或vbNewLine
时,可以解决此问题我现在使用的chr(11)
中的每一行中,每一行都以这样的框状问号开头: