Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 无法关闭在内存中运行的excel进程_Vb.net_Excel_Excel 2007_Vba - Fatal编程技术网

Vb.net 无法关闭在内存中运行的excel进程

Vb.net 无法关闭在内存中运行的excel进程,vb.net,excel,excel-2007,vba,Vb.net,Excel,Excel 2007,Vba,我开发了一个VB.Net代码,用于从excel文件中检索数据。我将这些数据加载到一个表单中,并在对数据进行必要的修改后将其更新回excel。这个完整的流程工作得很好,但大多数时候我观察到,即使我关闭表单;已加载的excel进程无法正确关闭 我尝试了所有可能的方法来关闭它,但无法解决问题。请查找我用于连接excel的以下代码,并告知我是否需要使用任何其他方法来解决此问题 注意:我不想终止excel进程,因为它将终止excel的其他实例 Dim connectionString作为字符串 conne

我开发了一个VB.Net代码,用于从excel文件中检索数据。我将这些数据加载到一个表单中,并在对数据进行必要的修改后将其更新回excel。这个完整的流程工作得很好,但大多数时候我观察到,即使我关闭表单;已加载的excel进程无法正确关闭

我尝试了所有可能的方法来关闭它,但无法解决问题。请查找我用于连接excel的以下代码,并告知我是否需要使用任何其他方法来解决此问题

注意:我不想终止excel进程,因为它将终止excel的其他实例

Dim connectionString作为字符串

connectionString=Provider=Microsoft.Jet.OLEDB.4.0;数据源=&ExcelFilePath&; 扩展属性=excel 8.0;持久安全信息=False

    excelSheetConnection = New ADODB.Connection

    If excelSheetConnection.State = 1 Then excelSheetConnection.Close()
    excelSheetConnection.Open(connectionString)
    objRsExcelSheet = New ADODB.Recordset

    If objRsExcelSheet.State = 1 Then objRsExcelSheet.Close()
    Try
        If TestID = "" Then
            objRsExcelSheet.Open("Select * from [" & ActiveSheet & "$]", excelSheetConnection, 1, 1)
        Else
            objRsExcelSheet.Open("Select Test_ID,Test_Description,Expected_Result,Type,UI_Element,Action,Data,Risk from [" & ActiveSheet & "$] WHERE TEST_Id LIKE '" & TestID & ".%'", excelSheetConnection, 1, 1)
        End If
        getExcelData = objRsExcelSheet
    Catch errObj As System.Runtime.InteropServices.COMException
        MsgBox(errObj.Message, , errObj.Source)
        Return Nothing
    End Try

    excelSheetConnection = Nothing
    objRsExcelSheet = Nothing

您正在使用旧的VB6 COM接口。在您的代码片段中没有任何证据表明您曾经在记录集上调用过Close。无法在连接上调用Close,因为已将其设置为Nothing

如前所述,在垃圾收集器运行且终结器线程释放COM接口上的引用计数之前,Excel不会退出。如果您的程序在处理数据后没有退出或进入休眠状态,这可能需要很长时间。你应该考虑提升这个代码来使用System.Data.Oledb中的类,这样当你完成对象时,你可以正确地处理所有的事情。 Q&D解决方案是强制终结器线程运行:

    GC.Collect()
    GC.WaitForPendingFinalizers()
    GC.Collect()
使用完记录集后运行此操作。不建议使用其他方法