Excel 中的另存为在 VB.net 上引发错误

SaveAs in Excel Throws an Error on VB.net

我正在尝试制作一个程序来修剪 excel 文件。我想保留原始文件,只是将新副本保存到具有修改名称的新目的地。我的代码给了我一个错误,我不确定我错过了什么。另外,有没有办法实际上只添加一个范围来删除 columns/rows 而不是一个一个地删除?

抛出异常:PO Trimmer.exe 中的 'System.Runtime.InteropServices.COMException' PO Trimmer.exe 中发生类型 'System.Runtime.InteropServices.COMException' 的未处理异常 无法访问该文件。尝试以下操作之一:

编译器不知道 Workbook 是什么与 Option Strict 开启(它应该总是开启)。由于我的 Imports 声明,我能够获得 Excel 资格。

我更改了消息框格式。这些值需要按位 Or 来组合正确的标志。

调用事件不是一个好主意。这可能会产生其他影响。将代码移至单独的方法并从此代码和按钮单击代码中调用它。

在满足条件之前,不要创建 Excel 对象。通过组合连续的范围,我能够稍微缩短代码。

退出不会完全清除互操作对象。互联网上有很多页面处理这个问题。

Imports Excel = Microsoft.Office.Interop.Excel

Private Sub btnBrowseDestination_Click(sender As Object, e As EventArgs) Handles btnBrowseDestination.Click
    BrowseDestination()
End Sub

Private Sub btnBrowseTarget_Click(sender As Object, e As EventArgas) Handles btnBrowseTarget.Click
    BrowseTarget()
End Sub

Private Sub BrowseTarget()
    'Code moved from btnBrowseTarget.Click
End Sub

Private Sub BrowseDestination()
    'Code moved from btnBrowseDestination.Click
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If txtTarget.Text = "" Then
        MsgBox("Please select the file you wish to convert!", MsgBoxStyle.Exclamation Or MsgBoxStyle.OkCancel, "Missing Target File")
        BrowseTarget()
    ElseIf txtDestination.Text = "" Then
        MsgBox("Please select the folder to save your file!", MsgBoxStyle.Exclamation Or MsgBoxStyle.OkCancel, "Missing Destination Folder")
        BrowseDestination()
    Else
        If rbtnSeca.Checked = True Then
            Dim xlApp As New Excel.Application()
            Dim xlBook As Excel.Workbook
            Dim xlSheet As Excel.Worksheet
            xlBook = xlApp.Workbooks.Open(txtTarget.Text)
            xlSheet = DirectCast(xlBook.Worksheets(1), Excel.Worksheet)
            Dim rg = DirectCast(xlSheet.Columns("H:N"), Excel.Range)
            rg.Select()
            rg.Delete()
            rg = DirectCast(xlSheet.Columns("D:F"), Excel.Range)
            rg.Select()
            rg.Delete()
            rg = DirectCast(xlSheet.Columns("A:B"), Excel.Range)
            rg.Select()
            rg.Delete()
            rg = DirectCast(xlSheet.Rows(1), Excel.Range)
            rg.Select()
            rg.Delete()
            Dim convertSuccess As Integer = MsgBox("Trimming success.", MsgBoxStyle.Information Or MsgBoxStyle.OkOnly, "Excel Trim")
            xlBook.SaveAs(txtDestination.Text & "PO_" & Today & "_" & TimeOfDay, Excel.XlFileFormat.xlOpenXMLWorkbook)
            xlApp.Quit()
        End If
    End If
End Sub