我有一些VBA代码在几个星期前完美运行,但现在崩溃了一个错误。从Word触发的代码用于打开Excel文件。我得到的具体错误与Activate方法有关。
Sub Populate()
Dim eApp As Excel.Application
Dim eWB As Excel.Workbook
Dim eSheet As Excel.Worksheet
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set eApp = New Excel.Application
End If
'Open Workbook
WorkbookName = "(Excel file location)"
eApp.Visible = True
eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
eWB.Activate
(etc.)
我是VBA新手,所以我确信有更好的方式来编写上述内容。它是最后一行--eWB.Activate - 它会产生编译错误,"找不到方法或数据成员。"再次,这是在上个月工作,现在还没有工作。 Office 2016中有什么变化导致此代码非法吗?
我玩了一遍,认为我有一个解决方法,但我仍然想知道为什么会崩溃,以备将来参考。感谢。
答案 0 :(得分:0)
我从单词中运行它并且它有效,我认为你有一个早期的绑定问题,这很可能是因为在你的机器上安装了一个新版本的单词。你可以google它并清理你的注册表以摆脱它。
Sub Populate()
Dim eApp As Object
Dim eWB As Object
Dim eSheet As Object
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set eApp = CreateObject("Excel.Application")
End If
'Open Workbook
WorkbookName = "\\grid\sasprod\ci\reports\Quickmarks\Quickmarks Tables A.xlsx"
eApp.Visible = True
eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
eWB.Activate
End Sub
答案 1 :(得分:0)
从那里开始On Error Resume Next
时,不知道为什么会出现该错误。您发布的内容中是否缺少代码?是否启用了Excel工作簿宏可能会干扰Word中的代码?
完成IntelliSense编码后,您也可以尝试使用Late Binding来处理这些Excel对象。只是为了演示如何编写Excel文件打开部件(Excel 2010):
Option Explicit
Sub Populate()
Dim eApp As Object ' Excel.Application
Dim eWB As Object ' Excel.Workbook
Dim eSheet As Object ' Excel.Worksheet
Dim ExcelWasNotRunning As Boolean
Dim WorkbookName As String
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If eApp Is Nothing Then Set eApp = CreateObject("Excel.Application")
ExcelWasNotRunning = eApp Is Nothing
If ExcelWasNotRunning Then Exit Sub
'Open Workbook
WorkbookName = "C:\Test\Tables.xlsx"
eApp.Visible = True
'eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
On Error GoTo 0 ' Turns on Debug prompt on Error
If Not eWB Is Nothing Then
With eWB
.Activate
' process stuff
.Save
.Close
End With
Set eWB = Nothing
End If
eApp.Quit
Set eApp = Nothing
End Sub