Excel 2016:从sharepoint以编程方式打开和关闭Excel文件

时间:2017-11-15 14:47:20

标签: vba excel-vba excel

我有这个测试代码,它试图启动一个隐藏的Excel进程,从一个位置加载一个Excel文件(" fileToOpen"),对该文件执行某些操作然后关闭该文件,最后关闭Excel处理。我在Excel 2016中执行测试。

Sub test()
    Dim excelapp As Object
    Dim wbk As Workbook

    Set excelapp = CreateObject("excel.Application")
    excelapp.Visible = True

    On Error GoTo error_handler

    Set wbk = excelapp.Workbooks.Open(filename:=fileToOpen, ReadOnly:=True)

    ' Do something

    wbk.Close SaveChanges:=False
    excelapp.Quit
    Set excelapp = Nothing

    Exit Sub

error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    excelapp.Quit
    Set excelapp = Nothing
End Sub

出于某种原因,当从SharePoint加载文件时,excelapp.Quit之后Excel进程保持活动状态,但是当从本地驱动器加载文件时,Excel进程将被终止。这在Excel 2010中也运行良好,即Excel过程已正确终止。

如果在阅读文件后正确关闭文件,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试更改

wbk.Close SaveChanges:=False
    excelapp.Quit
    Set excelapp = Nothing

到这个

    wbk.Close SaveChanges:=False
    Application.Quit
    Application.DisplayAlerts = False
    Set excelapp = Nothing

    error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    excelapp.Quit
    Set excelapp = Nothing

到这个

    error_handler:
    MsgBox "A problem occurred", vbOKOnly, "Error"
    Application.Quit
    Application.DisplayAlerts = False
    Set excelapp = Nothing