打开Word模板,将Excel数据粘贴并保存 [英] Open Word template, paste Excel data in and save

查看:121
本文介绍了打开Word模板,将Excel数据粘贴并保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got an Excel data range I need to be able to paste into a Word document template and save automatically using a macro from Excel.

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

Currently when it is run, it tells me the template file is already open/locked and I have to open a read only copy for it to continue. It does create and save the word file but when I try open the saved word doc it says there are problems with the contents..

我已经Googled很多,并认为我很亲近,但如果有人可以给我一些指针,将不胜感激。

I've Googled a lot and think I'm close but if anyone can give me some pointers that would be appreciated.

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

Try documents.add instead of documents.open

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

It will open an instance of the template, instead of the template itself

这篇关于打开Word模板,将Excel数据粘贴并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆