vba 从 Excel 中获取数据并插入到预先存在的 Word 表格中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23805804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:12:41  来源:igfitidea点击:

Taking data from Excel and inserting into a pre existing Word table?

excelvbaexcel-vbams-word

提问by Jaz

I know this has been asked previously, but I can only find sites which create the table in Word as you transfer the data.

我知道以前有人问过这个问题,但我只能找到在传输数据时在 Word 中创建表格的站点。

I have a Word document with 3 tables and want to extract data from an Excel file sent by a client into certain cells within the Word tables. E.G I would like to take the content of cell D3 in Excel and put it in cell 2,2 in the second table in Word? Is there a way to reference which table to insert the data?

我有一个包含 3 个表格的 Word 文档,想从客户端发送的 Excel 文件中提取数据到 Word 表格中的某些单元格中。EG 我想把 Excel 中单元格 D3 的内容放在 Word 中第二个表的单元格 2,2 中?有没有办法引用哪个表插入数据?

Can anyone help with this or just push me in the right direction as I am relatively new to Macros etc. As we use the Word document and have the Excel file sent to us, would making the Macro in Word be more beneficial or not?

任何人都可以帮助解决这个问题,或者只是将我推向正确的方向,因为我对宏等比较陌生。当我们使用 Word 文档并将 Excel 文件发送给我们时,在 Word 中使用宏是否更有益?

Thanks

谢谢

回答by Jaz

I have managed to fix it and typically it is relatively simple, but thanks to @David Zemens for the push in the right direction. I don't know how I missed the "Tables" bit out when searching through "ThisDocument" previously.

我已经设法修复它,通常它相对简单,但感谢@David Zemens 朝着正确的方向推动。我不知道我以前在搜索“ThisDocument”时怎么错过了“表格”。

 Sub GetData()

Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim ExcelFileName As String

ExcelFileName = "{Put the directory of Excel file here}"
Set exWb = objExcel.Workbooks.Open(ExcelFileName)

'Set the text of the cell from Excel to the cell in the specified table in Word (the second table in this instance)
ActiveDocument.Tables(2).Cell(2, 2).Range.Text = exWb.Sheets("Test").Cells(2, 1)

' Close Excel bits
exWb.Close
Set exWb = Nothing

End Sub