运行时错误91;将数据从Excel传输到Word表格
从我目前的发现来看,似乎很简单的事情让我感到困扰。我试图通过VBA将excel工作簿中的数据链接到word文档中的表。这是我找到的代码,到目前为止我做了一些轻微的修改运行时错误91;将数据从Excel传输到Word表格,excel,vba,ms-word,runtime-error,Excel,Vba,Ms Word,Runtime Error,从我目前的发现来看,似乎很简单的事情让我感到困扰。我试图通过VBA将excel工作簿中的数据链接到word文档中的表。这是我找到的代码,到目前为止我做了一些轻微的修改 Sub GetData() Dim strPath As String Dim strFileName As String Dim strFileExtension As String Dim strFullName As String strPath = "file path here"
Sub GetData()
Dim strPath As String
Dim strFileName As String
Dim strFileExtension As String
Dim strFullName As String
strPath = "file path here"
strFileName = "file name here"
strFileExtension = "Extension here"
strFullName = strPath & strFileName & strFileExtension
Set objWorkbook = objExcel.Workbooks.Open(strFullName)
'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(1).Cell(2, 2).Range.Text = objWorkbook.Sheets("Sheet1") _
.Cells(2, 1)
'Close Excel bits
objWorkbook.Close
Set objWorkbook = Nothing
End Sub
我发现的最初错误是没有在引用和简单语法错误中检查excel对象库。修复这些问题后,我现在得到一个“运行时错误91对象变量或未设置块变量”。当我试图设置OBJ工作簿变量时,会发生此错误。我已经声明了这些公共变量
Public objExcel As Excel.Application
Public objWorkbook As Excel.Workbook
Public objWorksheet As Excel.Worksheet
Public objRange As Excel.Range
然而,当我查找这个错误时,我发现我需要声明这些公共变量。不知道从这里到哪里去。如果有人能把我推向正确的方向,我将不胜感激。此外,感谢您迄今为止提供的所有帮助,本网站是一个救命稻草。试试以下方法:
Sub GetData()
Dim strPath As String
Dim strFileName As String
Dim strFileExtension As String
Dim strFullName As String
dim objExcel As Object, objWorkbook As Object
strPath = "file path here"
strFileName = "file name here"
strFileExtension = "Extension here"
strFullName = strPath & strFileName & strFileExtension
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(strFullName)
'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(1).Cell(2, 2).Range.Text = objWorkbook.Sheets("Sheet1").Cells(2, 1)
'Close Excel bits
objWorkbook.Close
objExcel.Quit
Set objWorkbook = Nothing
Set objExcel = Nothing
End Sub
顺便说一句,如果使用上面使用的CreateObject
函数,则不需要添加引用
您遇到了几个问题:
您已经声明了应用程序变量,但是您是否已经给了它一个值?i、 e.
Set objExcel=New Excel.Application
非常感谢!让它和这个一起工作。我真的很感谢你的帮助