Forum Discussion
wordnoob34572
May 12, 2023Copper Contributor
import text from excel into word
i have a use case that I'm hoping to see if i can automate. We have a word document that's about 100 pages long, in that word document we need to insert ~250 sentences at prescribed spots that ge...
May 13, 2023
wordnoob34572 You could insert DOCVARIABLE fields in the document for each of the Unique ID's and the whenever you get a new file, use code the iterate through the Excel data, setting the value of each of the Variables in the document to the data in the column to the right of the Unique ID and then have the code update the fields in the document so that each field displayed the data.
This code would be run from Word
Dim xlapp As Object
Dim xlbook As Object
With Dim xlsheet As Object
Dim i As Long
Dim bStartApp as Boolean
Dim FD As FileDialog
Dim strSource As String
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.Title = "Select the workbook that contains the data"
.Filters.Clear
.Filters.Add "Excel Workbooks", "*.xlsx"
.AllowMultiSelect = False
If .Show = -1 Then
strSource = .SelectedItems(1)
Else
MsgBox "You did not select the workbook that contains the data"
Exit Sub
End If
End With
bStartApp = False
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
If Err Then
bstartApp = True
Set xlapp = CreateObject("Excel.Application")
End If
On Error GoTo 0
Set xlbook = xlapp.Workbooks.Open(strSource)
Set xlsheet = xlbook.Worksheets(1)
With xlsheet.Range("A1")
For i = 1 to .CurrentRegion.Rows.Count - 1
ActiveDocument.Variables(.Offset(i,0).Value = .Offset(i, 1)
Next i
End WIth
xlbook.Close, False
If bStartApp = True Then
xlapp.Quit
End If
Set xlapp = Nothing
Set xlbook = Nothing
With ActiveDocument
.PrintPreview
.ClosePrintPreview
End With