运行时错误462使用Excel访问VBA

时间:2015-06-04 16:35:26

标签: excel ms-access access-vba runtime-error

尝试使用Access VBA打开/操作Excel文件时,偶尔会出现运行时错误。错误是

  

"运行时错误'':远程服务器计算机不存在或者是   不可用

令人沮丧的是,错误仅针对某些文件而不是其他文件发生,并且在不同的实例中。这是我的代码,错误发生在workbooks.open(sPath)行:

    DoCmd.SetWarnings False

Dim oExcel As New Excel.Application
Dim oWB As Workbook
Dim oWS As Worksheet

Set oExcel = Excel.Application
Set oWB = oExcel.Workbooks.Open(sPath)
Set oWS = oWB.Sheets(1)

oExcel.Visible = False

    If fGetFileName(sPath) = "FILE_NAME1.xlsx" Then
        'oExcel.Visible = False
        oWS.Range("AW1").Value = "TEXT1"
        oWS.Range("AX1").Value = "TEXT2"
        oWS.Range("AY1").Value = "TEXT3"
    End If

oWB.Save
Debug.Print "Amended " & sPath

oWB.Close False
Set oWB = Nothing

oExcel.Quit
Set oExcel = Nothing

DoCmd.SetWarnings True

经过一些网上研究后,我发现这份文件很好地概述了错误:https://anictteacher.files.wordpress.com/2011/11/vba-error-462-explained-and-resolved.pdf

使用该文档中的逻辑,错误是:

  

对象尚未通过引用Office对象完全限定   在每种情况下

但是,我修改了发生错误的行以专门引用Excel对象(设置oWB = oExcel .Workbooks.Open(sPath))。尝试将维度声明为对象,并在每次提及工作簿/工作表时引用oExcel。有任何想法吗? sPath需要更好的合格吗?

2 个答案:

答案 0 :(得分:1)

您将 oExcel 声明为新的Excel.Application

Dim oExcel As New Excel.Application

这意味着稍后在您的代码中,Set oExcel = Excel.Application并不真正有用......因为 oExcel 已经是对Excel.Application的引用。添加MsgBox以演示 oExcel 当时的内容......

MsgBox "TypeName(oExcel): " & TypeName(oExcel)
'Set oExcel = Excel.Application

为Excel对象变量考虑不同的方法。测试这个剥离过程(目的只是为了看它是否消除了你当前的错误):

Dim oExcel As Excel.Application
Dim oWB As Excel.Workbook

DoCmd.SetWarnings True

MsgBox "TypeName(oExcel): " & TypeName(oExcel)
Set oExcel = New Excel.Application
MsgBox "TypeName(oExcel): " & TypeName(oExcel)
Set oWB = oExcel.Workbooks.Open(sPath)
oWB.Close False
Set oWB = Nothing
oExcel.Quit
Set oExcel = Nothing

答案 1 :(得分:0)

另外,请使用WorkSheet并关闭它:

Set oWS = oWB.WorkSheets(1)
' snip.
oWB.Save
Set oWs = Nothing    
oWB.Close False
Set oWB = Nothing