0

我正在使用 Visual Studio .NET (VB) 所以如果你有 C# 的解决方案,请先到这里 ( http://converter.telerik.com/ )

我有一个带有文本的文档,以及要替换的单词数组:我需要替换纯文本并替换为实际的合并字段

Dim replacements(,) As String =
        New String(,) {{"[firstname]", "$Field.FName"},
               {"[lastname]", "$Field.LName"},
               {"[addr]", "$Field.Addr.St"},
               {"[city]", "$Field.City"}}

Dim dotXLoc "c:/test/result.dotx"

Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate  'SAVE AS DOT
Dim wordApp As Object = New Microsoft.Office.Interop.Word.Application()
Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open(dotXLoc)

' Get bounds of the array.
Dim bound0 As Integer = replacements.GetUpperBound(0)

' Loop over all elements.
For i As Integer = 0 To bound0
    ' Get element.
    Dim FieldFind As String = replacements(i, 0)
    Dim FieldReplace As String = replacements(i, 1)

        '<<< CODE HERE TO REPLACE TEXT WITH MERGEFIELD >>>
Next

currentDoc.SaveAs(dotXLoc & " v2.dotx", Fileformat)
currentDoc.Close()
wordApp.Quit()
4

1 回答 1

0

这是最终结果

 Public sub main()

            Dim rtfLoc = "c:/temp.rtf"
            Dim dotXLoc = "c:/temp.dotx"
            Dim Fileformat As Microsoft.Office.Interop.Word.WdSaveFormat = Word.WdSaveFormat.wdFormatXMLTemplate
            Dim wordApp As Word.Application = New Microsoft.Office.Interop.Word.Application()
            Dim currentDoc As Microsoft.Office.Interop.Word.Document = wordApp.Documents.Open(rtfLoc)


            TextToMergeField(currentDoc)

            currentDoc.SaveAs(dotXLoc, Fileformat)
            currentDoc.Close()
            wordApp.Quit()
 End Sub

我们从主函数中调用 TextToMergeField(currentDoc) 这样我们就可以遍历多个文档并替换所有实例

 Private Sub TextToMergeField(ByRef currentdoc As Word.Document)
    Dim rng As Word.Range
    Dim replacements(,) As String =
    New String(,) {{"[firstname]", "$Field.FName"},
           {"[lastname]", "$Field.LName"},
           {"[addr]", "$Field.Addr.St"},
           {"[city]", "$Field.City"}}
    Dim bound0 As Integer = replacements.GetUpperBound(0)
    currentdoc.Activate()
    For i As Integer = 0 To bound0
        rng = currentdoc.Range
        With rng.Find
            .Text = replacements(i, 0)
            Do While .Execute(Replace:=WdReplace.wdReplaceOne)
                currentdoc.Fields.Add(rng, WdFieldType.wdFieldMergeField, replacements(i, 1))
            Loop
        End With
    Next 
End Sub

希望这可以帮助某人

于 2015-06-08T18:31:57.857 回答