Vba 将Word文档范围设置为Excel范围
我有一个更大的项目,它帮助在Excel中根据其他工作表上的多个报告生成字母,并将每个字母输入到一个通用Word文档中,在每个字母之间插入分页符。我试图解决一个问题,其中随机抛出一个错误,指出剪贴板无效。以下代码有时会产生此错误: 易出错代码:Vba 将Word文档范围设置为Excel范围,vba,excel,Vba,Excel,我有一个更大的项目,它帮助在Excel中根据其他工作表上的多个报告生成字母,并将每个字母输入到一个通用Word文档中,在每个字母之间插入分页符。我试图解决一个问题,其中随机抛出一个错误,指出剪贴板无效。以下代码有时会产生此错误: 易出错代码: Sub ExportToWordDoc(ws As Worksheet, wordDoc As Word.Document, classCount As Long) Application.CutCopyMode = False ws.Ra
Sub ExportToWordDoc(ws As Worksheet, wordDoc As Word.Document, classCount As Long)
Application.CutCopyMode = False
ws.Range("A1:J" & classCount + 8).Copy
DoEvents 'added in attempt to resolve random error
Application.Wait (Now + TimeValue("0:00:01")) 'also added in attempt to resolve error
wordDoc.Range(wordDoc.Content.End - 1).Paste 'line causes intermittent error
wordDoc.Range(wordDoc.Content.End - 1).InsertBreak Type:=7
End Sub
我相信最终的解决方案将是避免使用剪贴板在服务器上迁移数据。有没有办法做到以下几点?目前,下面的代码产生类型不匹配错误
Sub ExportToWordDoc(ws As Worksheet, wordDoc As Word.Document, classCount As Long)
wordDoc.Range(wordDoc.Content.End - 1).Text = ws.Range("A1:J" & classCount + 8).value
wordDoc.Range(wordDoc.Content.End - 1).InsertBreak Type:=7
End Sub
任何帮助都将不胜感激
仅供参考:生成的字母数可以在10到100之间
编辑:更多信息。
也许您可以在这段代码中找到更好的方法。本例采用工作表1上的A1:A10范围,并将其导出到名为table Report的现有Word文档中的第一个表。注意:它不使用复制
Sub Export_Table_Data_Word()
'Name of the existing Word document
Const stWordDocument As String = "Table Report.docx"
'Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdCell As Word.Cell
'Excel objects
Dim wbBook As Workbook
Dim wsSheet As Worksheet
'Count used in a FOR loop to fill the Word table.
Dim lnCountItems As Long
'Variant to hold the data to be exported.
Dim vaData As Variant
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Sheet1")
vaData = wsSheet.Range("A1:A10").Value
'Instantiate Word and open the "Table Reports" document.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path &; "\" &; stWordDocument)
lnCountItems = 1
'Place the data from the variant into the table in the Word doc.
For Each wdCell In wdDoc.Tables(1).Columns(1).Cells
wdCell.Range.Text = vaData(lnCountItems, 1)
lnCountItems = lnCountItems + 1
Next wdCell
'Save and close the Word doc.
With wdDoc
.Save
.Close
End With
wdApp.Quit
'Null out the variables.
Set wdCell = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
MsgBox "The " &; stWordDocument &; "'s table has succcessfully " &; vbNewLine &; _
"been updated!", vbInformation
End Sub
您的Excel数据是一个表格,并且您正在从每行或某些行创建字母,就像在邮件合并中一样?如果是,请参见此。否则,请参见以下报告:谢谢;但是,我试图避免邮件合并。数据是从两个不同的工作表合并而来的,生成的用户数据存储为包含用户定义类的字典,其中每个对象包含各种数据,包括用户即将使用的类的集合。所以,如果作为邮件合并,我需要有一种方法为每封信提取多个可变项—有些有1个类,有些有10个。您没有给我们足够的信息。您要传递的ws.Range的内容是什么?你期望结果是什么?你想找张桌子吗?然后您需要插入一个表并逐个单元格填充它。无法将Excel信息表直接传递到Word.Range中。插入表格可能是一种方法。我会做一些研究,除非你有一个如何实现的例子。谢谢@Cindymeesternot right-off,没有。不过给你的提示是:将Excel数据写入一个字符分隔的字符串。将其指定给Word.Range。然后使用Word的Range.ConvertToTable方法。之后的任何格式。比逐个单元格的方法快得多/效率更高。我还没有时间应用这个方法,但这绝对是我想要的。谢谢