P
P
ProooNoob2022-01-10 21:01:09
Macros
ProooNoob, 2022-01-10 21:01:09

How to populate a table in a single Word document with data from an Excel spreadsheet using a VBA macro?

I welcome everyone! There was a task of automating the formation of a table in a Word document from data entered into an Excel table.
1. There is an Excel spreadsheet
. An example format is given below, with an indeterminate amount of input data, but with a strictly specified form. It is necessary when pressing a key to form a table in a Word document.
61dc706715143408717303.jpeg
2. There is a typical Word document itself
. The table in the document must be filled with data from the Excel table and, depending on the number of points (No. p / p), expand with fields (empty fields are given as an example).
61dc708dd3a68708761066.jpeg
3. There is an example of code I
found on the Internet: I thought I would remake it for my tasks, but I still don’t know where to start.

Sub main()
Dim wdApp As Object
Dim wdDoc As Object

HomeDir$ = ThisWorkbook.Path
Set wdApp = CreateObject("Word.Application")
i% = 2
Do
If Cells(i%, 1).Value = "" Then Exit Do
If Cells(i%, 1).Value <> "" Then

NPP$ = Cells(i%, 1).Text
ID$ = Cells(i%, 2).Text
Adress$ = Cells(i%, 3).Text
SN$ = Cells(i%, 4).Text

DataC$ = Date

FileCopy HomeDir$ + "\template.doc", HomeDir$ + "\" + NPP$ + "_" + ID$ + "_" + DataC$ + ".doc"
Set wdDoc = wdApp.Documents.Open(HomeDir$ + "\" + NPP$ + "_" + ID$ + "_" + DataC$ + ".doc")

wdDoc.Range.Find.Execute FindText:="&date", ReplaceWith:=DataC$

wdDoc.Range.Find.Execute FindText:="&id", ReplaceWith:=ID$
wdDoc.Range.Find.Execute FindText:="&adress", ReplaceWith:=Adress$
wdDoc.Range.Find.Execute FindText:="&sn", ReplaceWith:=SN$

wdDoc.Save
wdDoc.Close
End If

i% = i% + 1
Loop
wdApp.Quit
MsgBox "Готово!"

End Sub


Can you tell me how to implement this using VBA macros? I would be glad for any help, code examples, algorithm how to do it. I combed the forums, but did not find the necessary information, although the task is typical.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question