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

Run time error 462 Access VBA using Excel

我在尝试使用 Access VBA open/manipulate Excel 文件时偶尔会遇到 运行 时间错误。错误是

"Run-Time error '462': The remote server machine does not exist or is unavailable

令人沮丧的是,该错误仅针对某些文件而不是其他文件以及在不同情况下发生。这是我的代码,错误发生在 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

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

object has not been fully qualified by reference to the Office object in every case

不过,我修改了出错的行,专门引用了Excel对象(Set oWB = oExcel.Workbooks.Open(sPath)).已尝试将维度声明为对象,并在每次提及 workbook/sheet 时引用 oExcel。有任何想法吗? sPath 是否需要更好的资格?

您将 oExcel 声明为新 Excel.Application:

Dim oExcel As New Excel.Application

这意味着在您的代码后面,Set oExcel = Excel.Application 并不是很有用...因为 oExcel 已经是对 [=13= 的引用].添加一个 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

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

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