将字符串替换为位于文本框中的文档变量



我正在用DocVariable字段替换自动化文本字符串。唯一的问题是,当这些字符串,我将称为标签,是当标签位于"TextBox"控制。

我使用两个模块用DOCVARIABLES替换标签

* * *标记的例子:"DEPARTMENT_NAME"<字符串文本/em>

DOCVARIABLE例子:{DOCVARIABLE"Department_Name"* MERGEFORMAT}* * *


模块1

Public Function PopulateDocuments() As Boolean
Dim Department_Name As String
Department_Name = "Department_Name"
ReplaceWithDocVar "DEPARTMENT_NAME", "Department_Name"
End Function

模块2

Public Function ReplaceWithDocVar(strFind As String, strVarName As String) As Boolean
Dim oStory As Range
Dim TextColor As Range
Dim strDocName As String
Dim orgDocName As String
Dim orgPath As String
Dim intPos As Integer
Dim docpath As String
Dim docname As String
Application.DisplayAlerts = False
For Each oStory In ActiveDocument.StoryRanges
With oStory.Find
Do While .Execute(FindText:=strFind, MatchCase:=True, MatchWholeWord:=True)

oStory.Text = ""
'oStory.Text = wdBlue
oStory.Fields.Add Range:=oStory, _
Type:=wdFieldDocVariable, _
Text:=Chr(34) & strVarName & Chr(34), _
PreserveFormatting:=True
oStory.Collapse 0
Loop
End With
If oStory.StoryType <> wdMainTextStory Then
While Not (oStory.NextStoryRange Is Nothing)
Set oStory = oStory.NextStoryRange
With oStory.Find
Do While .Execute(FindText:=strFind, MatchCase:=True, MatchWholeWord:=True)
oStory.Text = ""
'oStory.Text = wdBlue
oStory.Fields.Add Range:=oStory, _
Type:=wdFieldDocVariable, _
Text:=Chr(34) & strVarName & Chr(34), _
PreserveFormatting:=True
'oStory.Font.ColorIndex = wdBlue
oStory.Collapse 0
Loop
End With
Wend
End If
Next oStory
Set oStory = Nothing
lbl_Exit:
Exit Function
End Function 

注意:我不是这段代码的作者,但它运行得很好。

在替换那些我可以定位的标签时,我没有看到任何错误消息。除文本框中的标签外,所有标签都被正确地替换为DOCVARIABLES。

文本框是文档中的形状。您必须在文档中搜索形状,然后确定形状是否是带有文本内容的TextBox。在任何情况下,对textbox的搜索以及对其文本内容的检查都必须与通过当前代码的文档故事范围进行的其他搜索分开。

下面是一些搜索文本框的示例代码。根据您的项目需要调整它。

Dim shp As Word.Shape
Dim rng As Word.Range
For Each shp In ActiveDocument.Shapes
If shp.Type = msoTextBox Then
If shp.TextFrame.HasText Then
Set rng = shp.TextFrame.TextRange
With rng.Find
'add your find and replace criteria here
End With
End If
End If
Next

最新更新