2015-10-13 36 views
-1

我有一個文檔模板.docx,我必須在特定點中編輯添加字符串。它看起來像如下:使用vba在文本的特定點添加內容

測試模式:這裏是一些文本已被添加,它可以採取更多的行,就應該在每一個縮進。
項目涉及:這裏是一些文本已被添加...
輸入和模擬參數:這裏是一些文本已被添加 ...

直到漢口我一直在使用下面的代碼

Sub FillingParagraphs() 
    Dim SubPara As Paragraph 
    Dim SubLevel As String 
    SubLevel = "3.1.1.1" 
    'Filling each subparagraph 
    For k = 1 To 3 
     For Each SubPara In ActiveDocument.Paragraphs 
      j = j + 1 
      If SubPara.Range.ListFormat.ListString = SubLevel Then 
       Selection.Start = ActiveDocument.Content.ListString 
      ActiveDocument.Paragraphs(j + 2).Range.Words(5) = "Text to be added" & Chr(10) 
      MsgBox j 
      End If 
     Next 
     'Update the string with the next subparagraph 
      SubLevel = "3.1.1." & CStr(k + 1) 
     j = 0 
    Next 
End Sub 

雖然它的工作原理,我需要指定確切點的地方開始寫計數的單詞和段落:

ActiveDocument.Paragraphs(j + 2).Range.Words(5) 

而且這種方式也不是那麼聰明,所以我想我modofy代碼是這樣的:

Selection.Start = ActiveDocument.Content.END_SUBSTRING_1 
Selection.TypeParagraph 
Selection.TypeText (" Text to be added") 

任何想法?

回答

0

也許你需要的東西是這樣的:

Sub InsertText(findWhat As String, insertAfter As String) 
    With ActiveDocument.Range.Find 
     .ClearFormatting 
     .Text = findWhat 
     .Replacement.ClearFormatting 
     .Replacement.Text = findWhat & " " & insertAfter 
     .MatchWholeWord = True 
     .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop 
    End With 
End Sub 

Sub test() 
    InsertText "some text to find", "some text to be added" 
End Sub 
+0

這是一個好的開始,因爲「我需要在每個findWhat上插入不同的文本」。我的意思是,我應該有這樣的東西,找到:first_Insert,findWhat:second_Insert等等。無論如何,這是非常有益的,非常感謝你! – vinx

0

我試圖改變過程中的以下內容,其中我給一個範圍內的功能來搜索:

Sub InsertText(findWhat As String, insertAfter As String, MyRange As Range) 
    With ActiveDocument.MyRange.Find 
     .ClearFormatting 
     .Text = findWhat 
     .Replacement.ClearFormatting 
     .Replacement.Text = findWhat & " " & insertAfter 
     .MatchWholeWord = True 
     .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop 
    End With 
End Sub 

所以在另一部分代碼中,我定義了一個範圍並將其設置爲默認值,然後根據我的需要重新設置範圍:

Level1 = "3.1.1.1" 
Level2 = "3.1.1.2" 

'定義使用默認值

Dim MyRange As Range 
Dim StartRange As Integer 
Dim EndRange As Integer 
Set MyRange = ActiveDocument.Range(0, 0) 

MyRange' 重新定義MyRange

For Each RngPara In ActiveDocument.Paragraphs 
     i = i + 1 
     If RngPara.Range.ListFormat.ListString = Level1 Then 
     StartRange = i 
     ElseIf RngPara.Range.ListFormat.ListString = Level2 Then 
     EndRange = i 
     End If 

     MyRange.SetRange  Start:=MyRange.Start,End:=ActiveDocument.Paragraphs(3).Range.End 
Next 
InsertText "Scope of test:", Scopo(j), MyRange 

它不反正工作!那有什麼問題?