vba 如何从 Word 获取对打开的 Excel 电子表格的引用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12682682/
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-11 17:56:09  来源:igfitidea点击:

How to get reference to an open Excel spreadsheet from Word?

excelvbams-wordword-vba

提问by user1713174

I have some VBA code that copies stuff from Excel and pastes it into Word. The problem I'm having is how to open the spreadsheet. I can open it using an absolute path reference by

我有一些 VBA 代码可以从 Excel 复制内容并将其粘贴到 Word 中。我遇到的问题是如何打开电子表格。我可以使用绝对路径引用打开它

Workbooks.Open "C:\path\filename.xls"

Workbooks.Open "C:\path\filename.xls"

I would prefer to reference the spreadsheet using a relative path reference. I was able to find code for relative path references from an Excel workbook to another one but it doesn't seem to work if you're doing it from Word.

我更愿意使用相对路径引用来引用电子表格。我能够找到从 Excel 工作簿到另一个工作簿的相对路径引用的代码,但如果您从 Word 中执行此操作,它似乎不起作用。

回答by KFleschner

Add a reference to Excel object library, then create an object in code and use that object to control an instance of Excel. Just make sure to avoid things like ActiveWorkbook, just in case.

添加对 Excel 对象库的引用,然后在代码中创建一个对象并使用该对象来控制 Excel 的实例。只要确保避免使用 ActiveWorkbook 之类的东西,以防万一。

After adding the reference:

添加参考后:

Sub DoStuffWithExcelInWord()
   Dim xl As Excel.Application
   Dim wkbk As Excel.Workbook
   Dim wk As Excel.Worksheet
   Set xl = CreateObject("Excel.Application")
   Set wkbk = xl.Workbooks.Open("C:\test.csv")
   Set wk = wkbk.Sheets(1)
   Debug.Print wk.Cells(1, 1).Value
   xl.Quit
   Set wk = Nothing
   Set wkbk = Nothing
   Set xl = Nothing
End Sub

You can create something very similar using Excel to automate Word too, if that's more of what you're looking for.

如果您正在寻找更多内容,您也可以使用 Excel 创建一些非常相似的东西来自动化 Word。