打开Word模板,粘贴Excel数据并保存

我有一个Excel数据范围,我需要能够粘贴到Word文档模板中,并使用Excel中的macros自动保存。

目前它运行时,它告诉我模板文件已经打开/locking,我必须打开一个只读副本才能继续。 它确实创build并保存word文件,但是当我尝试打开保存的word文档时,表示存在内容问题。

我GOOGLE了很多,认为我很接近,但如果任何人都可以给我一些指针,将不胜感激。

Option Explicit Sub CopyExcelDataToWord2() Dim wdApp As New Word.Application Dim wdDoc As Word.Document Dim wsSource As Excel.Worksheet Dim docWordTarget As Object Dim SaveAsName As String Dim customSavePath As String Dim nameFile, WordName2 Dim ColRange As Range Set wdDoc = wdApp.Documents.Open("C:\test\templ.dotx") wdApp.Visible = True 'Cell with the filename to save final doc as nameFile = Sheets("Form").Cells(70, 1).Value 'Gets the file path from cell and adds variable 'nameFile' value to the end customSavePath = Worksheets("Form").Cells(57, 1).Value & "\" & nameFile & ".docx" 'sets the variable wsSource to the activesheet Set wsSource = ThisWorkbook.ActiveSheet Set ColRange = Sheets("Form").Range("A1:D54") 'if no data is selected then exit sub If ColRange Is Nothing Then Exit Sub 'sets variable WordName2 to the selected columns address Else 'sets variable WordName2 to column Range WordName2 = ColRange.Address End If 'With word document make visible and select With wdApp .Visible = True Set docWordTarget = .Documents.Open("C:\test\templ.dotx") .ActiveDocument.Select End With 'With excel workbook copy the column selected previously With wsSource .Range(WordName2).Copy End With 'Paste data into word doc With wdApp.Selection .PasteExcelTable linkedtoexcel:=False, wordformatting:=False, RTF:=False .TypeParagraph End With With wdApp 'Save word doc in the custom save path .ActiveDocument.SaveAs Filename:=customSavePath .ActiveWindow.Close ' Kill the Object .Quit End With MsgBox "Exported To:" & vbNewLine & vbNewLine & (customSavePath) Set docWordTarget = Nothing Set wdApp = Nothing Application.CutCopyMode = False End Sub 

试试documents.add而不是documents.open

它将打开模板的实例,而不是模板本身

首先,由于单词的实例仍在后台运行,并locking要重新打开的文件,因此会出现locking错误。 你可以用任务pipe理器来validation。 为了避免这个错误,你可以:

  • 杀死任务pipe理器中的WinWord.exe进程
  • 使用wdApp.documents.Add而不是.open

或(最好)

  • 编写一个函数,让字应用程序在后台运行,或者如果没有,创build一个新的。 这是IMO的最佳select,因为您不会有在后台运行许多不可见的Word进程的风险。

     Private Function GetWordApp() As Word.Application On Error Resume Next Set GetWordApp = GetObject(, "Word.Application") If GetWordApp Is Nothing Then Set GetWordApp = New Word.Application End Function