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

时间:2015-09-23 12:31:29

标签: excel vba excel-vba ms-word

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

目前,当它运行时,它告诉我模板文件已经打开/锁定,我必须打开一个只读副本才能继续。 它确实创建并保存了单词文件,但是当我尝试打开保存的单词doc时,它说内容存在问题..

我已经搜索了很多并且认为我已经关闭但是如果有人能给我一些可以欣赏的指示。

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

2 个答案:

答案 0 :(得分:2)

尝试使用documents.add而不是documents.open

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

答案 1 :(得分:2)

首先,您遇到锁定错误,因为word的实例仍在后台运行并锁定您尝试重新打开的文件。您可以使用任务管理器验证。要避免此错误,您可以:

  • 在任务管理器中终止WinWord.exe进程
  • 使用wdApp.documents.Add而不是.open

或(最佳)

  • 编写一个函数,可以让word应用程序在后台运行,如果没有,则创建一个新函数。这是IMO的最佳选择,因为您不会有在后台运行许多不可见的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