Я обновил код, проверил и дал мне знать, если он работает?
Перед запуском макроса перейдите в Microsoft Visual Basic для приложений, окно
, затем в Инструменты-> Ссылки
и проверьте «библиотеку объектов Microsoft Word xx»
и ok
, затем удалите таблицу, вставленную в шаблон, и сохраните ее, так как макрос вставит ее,вам не нужны два из них.
Обновлен макрос
Sub runMacro()
save_path = ThisWorkbook.Path & "\"
Call makeDocument("Name 1", save_path)
Call makeDocument("Name 2", save_path)
Call makeDocument("Name 3", save_path)
End Sub
Sub makeDocument(sheet_name, save_path)
'Remember: this code requires a referece to the Word object model
'dimension some local variables
Dim rng As Range 'our source range
Dim wdApp As New Word.Application 'a new instance of Word
Dim wdDoc As Word.Document 'our new Word document
Dim t As Word.Range 'the new table in Word as a range
Dim myWordFile As String 'path to Word template
'initialize the Word template path
'here, it's set to be in the same directory as our source workbook
myWordFile = ThisWorkbook.Path & "/Word Template.docx"
'get the range of the contiguous data from Cell A1
'Set rng = Range("A1").CurrentRegion
Set rng = Sheets(sheet_name).Range("A1:E23")
'you can do some pre-formatting with the range here
'rng.HorizontalAlignment = xlCenter 'center align the data
rng.Copy 'copy the range
'open a new word document from the template
Set wdDoc = wdApp.Documents.Add(myWordFile)
'wdDoc.Paragraphs(2).Range.PasteExcelTable False, False, flase
Set t = wdDoc.Content 'set the range in Word
Set t = wdDoc.Paragraphs(2).Range
t.Paste 'paste in the table
With t 'working with the table range
'.Style = "Strong" 'set the style created for the table
'.Style = "Grid Table 4 - Accent 2"
'we can use the range object to do some more formatting
'here, I'm matching the table with using the Excel range's properties
.Tables(1).Columns.SetWidth (rng.Width / rng.Columns.Count), wdAdjustSameWidth
End With
'until now the Word app has been a background process
wdApp.Visible = True
'we could use the Word app object to finish off
'you may also want to things like generate a filename and save the file
wdApp.Activate
file_name = save_path & sheet_name 'set the directory where files would be saved
'save file
wdDoc.SaveAs2 Filename:=file_name, FileFormat:= _
wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False, CompatibilityMode:=15
End Sub