简体   繁体   English

将Excel数据导出到Word模板

[英]Export excel data to word template

ID          Employee    Date       
1234        me          11/03/2015
9999        U           11/03/2015
1111        Us          11/03/2015 

Hi, 你好

I have the above table in excel that is populated when a user completes a userform and clicks a 'Save' Button. 我在excel中有上面的表格,当用户填写用户表格并单击“保存”按钮时,该表格已填充。 Once they have saved an 'Export' button is enabled and the user can export the last record (row) submitted by the user form to a word template in the relevant locations on the template. 保存后,将启用“导出”按钮,用户可以将用户表单提交的最后一条记录(行)导出到模板上相关位置的单词模板。 I have created bookmarks in the attached word template for ID,Employee and Date and would like the data to be exported to these locations. 我已经在附加的单词模板中为ID,Employee和Date创建了书签,并且希望将数据导出到这些位置。

I've written the following code on the 'Export' button but I can't seem to get the export to work. 我已经在“导出”按钮上编写了以下代码,但似乎无法使导出正常工作。 the code runs up until the template is opened but the posting of the data to the bookmarks causes an error. 代码将一直运行到打开模板为止,但是将数据发布到书签会导致错误。

Sub PDFExportRow()
    Dim WRD As Object, DOC As Object, ac As Long
    On Error Resume Next
    Set WRD = CreateObject("Word.Application")
    If Err.Number <> 0 Then
  Set WRD = CreateObject("Word.Application")
  End If
  On Error GoTo 0

  Set DOC = WRD.Documents.Open("C:\RC_QA_TEST\Template\QA_REPORT.dotm")


WRD.Visible = True
ac = ActiveCell.Row

With DOC
.FormFields("ID").Result = Cells(ac, "A")
.FormFields("Employee").Result = Cells(ac, "B")
.FormFields("Date").Result = Cells(ac, "C")

End With

'set active printer to one you use here
WRD.ActivePrinter = "CutePDF Writer"
'print document
DOC.PrintOut
'close document without saving
DOC.Close False
'close application
WRD.Quit
Set WRD = Nothing
Set DOC = Nothing


End Sub

Any help on this is greatly appreciated. 在此方面的任何帮助将不胜感激。

If the code is having errors starting with the DOC.FormFields part, then I think the problem is that you haven't actually used Form Fields, you have used bookmarks, so you need to use the appropriate methods. 如果代码以DOC.FormFields部分开头有错误,那么我认为问题是您实际上没有使用过Form Fields,而是使用了书签,因此需要使用适当的方法。

Try this: 尝试这个:

With DOC
.Bookmarks("ID").Range.Text = Cells(ac, "A")
.Bookmarks("Employee").Range.Text = Cells(ac, "B")
.Bookmarks("Date").Range.Text = Cells(ac, "C")

End With

Note that once you update the text in a bookmark, the bookmark is removed from the document. 请注意,一旦更新了书签中的文本,便会将书签从文档中删除。 Since you are closing the document without saving it, when you reopen, the bookmark will be there again, but you would need to reset the bookmark if you were to save the word doc, or keep it open and try to replace the text again. 由于要关闭文档而不保存文档,因此,当您重新打开书签时,书签将再次存在。但是,如果要保存单词doc或使其保持打开状态并尝试再次替换文本,则需要重置书签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM