【发布时间】:2019-11-06 16:24:30
【问题描述】:
我正在编写一个 VBA 脚本来从已定义的模板生成 word 文档。在其中,我需要能够编写标题以及每个标题的正文。作为一个小例子,我有一个只包含<PLACEHOLDER> 的word 文档。对于我需要编写的每个标题和正文,我使用 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) 时,我现在正在使用,每一行都以这样的带框问号开头:
【问题讨论】:
-
为什么要在替换的文本中添加“
”?文件不包含这些?如果是这样的话,肯定会有更好的编码方式...... -
@CindyMeister,我在每次替换后添加
<PLACEHOLDER>,以便 next 查找和替换将能够“找到”它并知道在哪里插入文本。它每次都被替换,最后一个被替换为新行(chr(11)),这就是为什么最终文档中没有出现<PLACEHOLDER>s。这是我想出的方法,但我对 vba 不是很熟悉,所以可能有更好的方法