Reputation: 341
I have been building a code to transfer data from excel to word. To try that out I have built a code with an array list. To check each array in the word and place a string next to the list. But it is not taking the array in the loop.
Sub CreateNewWordDoc()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim i As Integer
Dim arr(12)
arr(0) = "(249_L), 38,7 %"
arr(1) = "(248_R), 38,7 %"
arr(2) = "(249_M), 38,7 "
arr(3) = "(3560), 38,7 "
arr(4) = "(3550), 38,7 %"
arr(5) = "(349_), 38,7 %"
arr(6) = "(348_), 38,7 %"
arr(7) = "(451), 38,7 %"
arr(8) = "(450L), 38,7 "
arr(9) = "(450R), 38,7 "
arr(10) = "(151), 38,7 %"
arr(11) = "(150L), 38,7 %"
arr(12) = "(150R), 38,7 %"
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("E:\ShareDrive_Ruehl\full-flexible-MBS-models_report\example-report\FullFlexibleGearbox - Copy (2).docx")
For i = 0 To 12
wrdDoc.Application.Selection.Find.Text = arr(i)
wrdDoc.Application.Selection.Find.Execute
wrdDoc.Application.Selection.InsertBefore arr(i) & "test"
Next
End Sub
I am getting the output as seen in the figure. My intention was to find "arr(i)
" and place arr(i)
text before it. But it is just finding array (0)
and pasting arr(i)
text.
Upvotes: 1
Views: 74
Reputation: 2917
Here is your code slightly adjusted. Note the use of With
blocks for a slightly more "cleaned up" look, and the HomeKey to reset the selection before the next find:
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim i As Integer
Dim arr(12)
arr(0) = "(249_L), 38,7 %"
arr(1) = "(248_R), 38,7 %"
arr(2) = "(249_M), 38,7 "
arr(3) = "(3560), 38,7 "
arr(4) = "(3550), 38,7 %"
arr(5) = "(349_), 38,7 %"
arr(6) = "(348_), 38,7 %"
arr(7) = "(451), 38,7 %"
arr(8) = "(450L), 38,7 "
arr(9) = "(450R), 38,7 "
arr(10) = "(151), 38,7 %"
arr(11) = "(150L), 38,7 %"
arr(12) = "(150R), 38,7 %"
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open("E:\ShareDrive_Ruehl\full-flexible-MBS-models_report\example-report\FullFlexibleGearbox - Copy (2).docx")
wrdDoc.Activate
wrdApp.Selection.HomeKey unit:=wdStory
For i = 0 To 12
With wrdApp.Selection
With .Find
.ClearFormatting
.MatchWildcards = False
.MatchWholeWord = False
.text = arr(i)
.Execute
End With
.InsertBefore arr(i) & "test"
.HomeKey unit:=wdStory
End With
Next
Note: your needs can most probably be achieved without using Selection
but further info would be needed for that.
Upvotes: 1