Can't properly close Excel application

北城余情 提交于 2021-01-29 08:53:18

问题


i am very new to VB.net and i'm trying to proceed step by step with my application. The application i'm trying to build will collect a series of macros i've written in Excel VBA environment. Now, the following code pasted below, is the initial part, where basically i try to load a workbook (to be used as Active workbook) and to "unload it". The issue comes when, after "unloading" the workbook, i try to open the very same workbook in excel. Excel application return an error that is "Open in read-only". This cannot be accepted, and i need to understand how to unload the workbook and release it from the 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

来源:https://stackoverflow.com/questions/61176667/cant-properly-close-excel-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!