簡體   English   中英

無法從Excel刪除工作表,甚至使用VB.NET沒有錯誤?

[英]Unable to delete sheet from excel and it even gives no error using VB.NET?

我有:

Public Class ExcelProcess
    Private App As New Excel.Application
    Private Books As Excel.Workbooks = App.Workbooks
    Private WB As Excel.Workbook

Public Sub deleteSheets()
    Dim sheet As Excel.Worksheet = getSheetToDelete()
    sheet.Activate()
    sheet.Delete()
    WB.Save()
    WB.Close()
End Sub

Private Function getSheetToDelete() As Excel.Worksheet
     Try
        WB = Books.Open("file.xlsx")
    Catch ex As Exception
        InputOutput.print(ex.Message)
        End
    End Try
    Return WB.Sheets(1)
End Function

End Class

我運行上面的代碼, 它成功運行,絕對沒有錯誤或異常!

但是這張表沒有被刪除!

<更新>

我也嘗試過:

sheet.Select()
sheet.Delete()

' Now, this gave me an exception:
Unhandled Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800A03EC
at Microsoft.Office.Interop.Excel._Worksheet.Select(Object Replace)
at DealerCapReport.ExcelProcess.deleteSheets()
at DealerCapReport.MainModule.Main()

<另一個更新>

我試圖檢查sheet.Delete()boolean是否成功失敗:

If sheet.Delete() Then        ' Error: Expression does not produce a value.
    Console.WriteLine("Can-not Delete")
End If

它表示錯誤:表達式不會產生值。 在sheet.Delete()中。

奇怪的是, Microsoft API引用說它會生成一個布爾值,但它不是因為它是Sub而不是函數。

怎么樣,發生了什么?

難道我做錯了什么?

請幫我解決這個問題!

以下代碼適用於我( EDITED包括一些錯誤檢查 ):

Public Class ExcelProcess
    Private xlApp As Excel.Application
    Private xlBook As Excel.Workbook
    Private xlSheet As Excel.Worksheet

    Public Sub New(ByVal file As String)
        xlApp = New Excel.Application
        'xlApp.Visible = True 'for debugging
        xlApp.DisplayAlerts = False 'prevent user dialogs
        xlBook = xlApp.Workbooks.Open(file)
    End Sub

    Public Sub Quit()
        If Not IsNothing(xlBook) Then
            xlBook.Save()
            xlBook.Close()
        End If
        If Not IsNothing(xlApp) Then xlApp.Quit()
    End Sub

    Public Sub deleteSheet(ByVal Index As Integer)
        If Index > xlBook.Worksheets.Count Then
            Throw New Exception("You cannot delete a worksheet that does not exist")
            Exit Sub
        End If
        If xlBook.Worksheets.Count = 1 Then
            Throw New Exception("You cannnot delete the only worksheet in a workbook")
            Exit Sub
        End If
        xlSheet = CType(xlBook.Worksheets(Index), Excel.Worksheet)
        xlSheet.Activate()
        xlSheet.Delete()
    End Sub

End Class

我建議您在執行刪除后使用SaveAs保存工作簿。 否則它只會刪除內存中的工作表,當您的Excel對象超出范圍時,它將關閉工作簿而不保存更改。

Books.SaveAs(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM