如何在标题中插入字段

时间:2017-07-19 15:28:24

标签: vba word-vba

我正在尝试在Word文档的标题中插入字段,而不是在它们之前或之后。这是为了准备导入到Madcap Flare的Word文件,它允许在私有Word字段中指定文件名。以下代码不起作用,因为该字段在标题开始之前附加,它需要嵌入其中。我怎样才能做到这一点。

Sub prepareDocForImport()
    Dim headingText As String '  
        With Selection.Find  
         .ClearFormatting  
         .Wrap = wdFindContinue  
         .Forward = True  
         .Format = True  
         .MatchWildcards = False  
         .Text = ""  
         .Style = ActiveDocument.Styles("Heading 1 ")  
         .Execute  
         While .Found  
             headingText = Selection.Range.Text  
             headingText = Replace(headingText , " ", "_")  
             headingText = LCase(headingText )  
             Selection.Collapse Direction:=wdCollapseStart  
             Set myField = ActiveDocument.Fields.Add(Range:=Selection.Range, Type:=wdFieldEmpty, Text:="PRIVATE:MADCAP:FILENAME<" & headingText & ">")  
            .Execute  

         Wend
     End With
End Sub

1 个答案:

答案 0 :(得分:0)

尝试将光标移动一个字符到标题字中。

我还添加了一行来确保搜索从文档的开头开始。

Sub prepareDocForImport()

    Dim headingText As String
    Dim myfield As Field

    'Moving to beginning of doc in case a different starting point is selected
    Selection.HomeKey wdStory

        With Selection.Find
         .ClearFormatting
         .Wrap = wdFindContinue
         .Forward = True
         .Format = True
         .MatchWildcards = False
         .Text = ""
         .Style = ActiveDocument.Styles("Heading 1 ")
         .Execute

         While .Found

             headingText = Selection.Range.Text
             headingText = Replace(headingText, " ", "_")
             headingText = LCase(headingText)
             Selection.Collapse Direction:=wdCollapseStart

             'Move seleection one character into the header text
             Selection.MoveRight Count:=1

             Set myfield = ActiveDocument.Fields.Add(Range:=Selection.Range, _
                                                     Type:=wdFieldEmpty, _
                                                     Text:="PRIVATE:MADCAP:FILENAME<" & headingText & ">", _
                                                     PreserveFormatting:=True)
             .Execute

         Wend
     End With
End Sub