无法正确关闭Excel应用程序

时间:2020-04-12 19:02:24

标签: excel vba

我是VB.net的新手,我正在尝试逐步处理我的应用程序。 我试图构建的应用程序将收集我在Excel VBA环境中编写的一系列宏。 现在,下面粘贴的以下代码是初始部分,基本上,我尝试在其中加载工作簿(用作Active工作簿)并“卸载”。 问题出在“卸载”工作簿后,我尝试在excel中打开完全相同的工作簿时。 Excel应用程序返回“以只读方式打开”错误。这是无法接受的,我需要了解如何卸载工作簿并从myAPP中释放它。

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    Dim workbook As Excel.Workbook
    Dim worksheet As Excel.Worksheet
    Dim APP As New Excel.Application

Private Sub opn_btn_Click(sender As Object, e As EventArgs) Handles opn_btn.Click
    Dim strname As String
    Dim cellname As String

    With OpenFileDialog1
        .InitialDirectory = "E:\Vs_Excel"
        .Title = "Open xlsx file"
        .ShowDialog()
    End With

    workbook = APP.Workbooks.Open(OpenFileDialog1.FileName)
    worksheet = workbook.Worksheets("sheet1")
    cellname = worksheet.Range("A1").Value

    strname = OpenFileDialog1.FileName
    Me.TextBox1.Text = strname
    Me.TextBox2.Text = cellname

    Dim lvwReport As View = View.List
    With Me.ListView1
        .GridLines = True
        .View = lvwReport
        .CheckBoxes = True
    End With

    'LoadListView() 'thi sroutine is written but not used yet. Must solve first the problem wioth closing ExcelApplication

End Sub


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    workbook.Close()
    APP.Quit()

    Me.TextBox1.Text = ""
    Me.TextBox2.Text = ""

    ReleaseObject(worksheet)
    worksheet = Nothing
    ReleaseObject(workbook)
    workbook = Nothing
    ReleaseObject(APP)
    APP = Nothing

End Sub
Private Sub ReleaseObject(ByVal obj As Object)
    Try
        Dim intRel As Integer = 0
        Do
            intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
        Loop While intRel > 0
        MsgBox("Final Released obj # " & intRel)
    Catch ex As Exception
        MsgBox("Error releasing object" & ex.ToString)
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub
End class

0 个答案:

没有答案