在VBA中打开Excel文件:运行时错误“462”:远程服务器计算机不存在或不可用

时间:2015-10-21 07:39:58

标签: excel vba excel-vba

我需要创建打开Excel文件的宏并在Workbook中保存一些文件。问题是,当我想在短时间内多次运行宏时(不幸的是我真的需要这样做),我收到错误' 462':远程服务器机器不存在或不可用。

我读到了这个并尝试修复它:我在开始时创建了特殊模块来杀死Excel进程:

Call KillExcel

Function KillExcel()

Dim oServ As Object
Dim cProc As Variant
Dim oProc As Object

Set oServ = GetObject("winmgmts:")
Set cProc = oServ.ExecQuery("Select * from Win32_Process")

For Each oProc In cProc

    'Rename EXCEL.EXE in the line below with the process that you need to Terminate.
    'NOTE: It is 'case sensitive

    If oProc.Name = "EXCEL.EXE" Or oProc.Name = "EXCEL.EXE *32" Then
     ' MsgBox "KILL"   ' used to display a message for testing pur
      errReturnCode = oProc.Terminate()
    End If
Next

End Function

但不幸的是,即使我关闭了这个过程,我仍然会收到这个错误。我使用Excel的代码部分如下所示:

Dim ark As Excel.Workbook
Dim xlSheet As Excel.Worksheet

Set ark = Excel.Workbooks.Open(FileName:=scexcel)
Set xlSheet = ark.Worksheets("Sheet1")
a = Sheets("Sheet1").Range("B" & Rows.Count).End(xlUp).Row + 1


Cells(a, 2).Value = "ABC"
Cells(a, 3).Value = "DEF"
Cells(a, 4).Value = "GHI"
Cells(a, 5).Value = "JKL"

a = a + 1

Set xlSheet = Nothing
ark.Close SaveChanges:=True

Set ark = Nothing

如果它可以帮到你,那么每次宏观崩溃(当我在短时间内运行多次时)就行了:

Set ark = Excel.Workbooks.Open(FileName:=scexcel)

scexcel是我的计算机上Excel文件所在的路径。你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

这应该对你有用(确保你先杀死先前代码中遗留的任何隐藏的Excel.exe实例):

Dim ark                   As Excel.Workbook
Dim xlSheet               As Excel.Worksheet
Dim a                     As Long

Set ark = GetObject(scexcel)
ark.Application.Visible = True
Set xlSheet = ark.Worksheets("Sheet1")
With xlSheet
    a = .Range("B" & .Rows.Count).End(xlUp).Row + 1
    .Cells(a, 2).Value = "ABC"
    .Cells(a, 3).Value = "DEF"
    .Cells(a, 4).Value = "GHI"
    .Cells(a, 5).Value = "JKL"
End With
Set xlSheet = Nothing
ark.Close SaveChanges:=True

Set ark = Nothing