2017-07-19 53 views
0

我試圖在Word文檔中的標題內插入字段,而不是在它們之前或之後。這是準備Word文件導入到Madcap Flare,它允許在專用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 

回答

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