使用Visual Basic和Interop从Excel中删除工作表

我有一个子程序,应该用非数字名称删除工作表。 这是find工作表,但不删除它们。 我无法弄清楚为什么….

这不是抛出错误,它创buildPDF(所有表)。 如果我将xlsBook.Close设置为保存更改,则工作簿在进程运行后仍具有所有工作表。

我正在使用MSOffice 2013Visual Studio 2015中运行此操作。 这是代码片段;

  Imports System Imports System.IO Imports Microsoft.Office.Interop.Excel Imports Microsoft.Office.Interop.PowerPoint Imports Microsoft.Office.Interop.Word Imports Microsoft.Office.Core Private Sub Convert_Excel(ByVal InFormat As String, ByVal InSpecial As String) Dim xlsApp = New Microsoft.Office.Interop.Excel.Application() Dim xlsBook As Microsoft.Office.Interop.Excel.Workbook Dim xlsSheet As Microsoft.Office.Interop.Excel.Worksheet xlsApp.Application.DisplayAlerts = False Try xlsApp.ScreenUpdating = False xlsBook = xlsApp.Workbooks.Open(theFile, UpdateLinks:=False, ReadOnly:=False) For Each xlsSheet In xlsBook.Sheets If Not IsNumeric(xlsSheet.Name) Then Try xlsSheet.Delete() Catch ex As Exception Environment.ExitCode = ERROR_EXCEL_NOSHEETS End Try End If Next If xlsBook.Worksheets.Count > 1 And Environment.ExitCode <> ERROR_EXCEL_NOSHEETS Then If LCase(InFormat) = "standard" Then xlsBook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, thePDFFile, XlFixedFormatQuality.xlQualityStandard, True, True, Type.Missing, Type.Missing, False, Type.Missing) Else Environment.ExitCode = ERROR_EXCEL_BADOP If Not Command_In Then System.Windows.Forms.MessageBox.Show("INVALID OPERATION SELECTED") End If End If End If xlsBook.Close(SaveChanges:=False) xlsApp.Quit() xlsBook = Nothing xlsApp = Nothing pdfnameLabel.Text = "Created " & Convert_FilePDF Catch ex As Exception Environment.ExitCode = ERROR_EXCEL_UNKNOWN If Not Command_In Then System.Windows.Forms.MessageBox.Show(ex.Message) End If Finally If xlsBook IsNot Nothing Then xlsBook.Close(SaveChanges:=False) End If If xlsApp IsNot Nothing Then xlsApp.Quit() End If End Try End Sub 

现在,就像@蒂姆威廉姆斯所说的那样。 我不知道你为什么不在这里得到错误 – 你应该在某个时刻

 For Each xlsSheet In xlsBook.Sheets If Not IsNumeric(xlsSheet.Name) Then Try xlsSheet.Delete() ' <-- should error here . . . . . . . . 

你应该使用While循环来改变集合。

 Dim index as Integer While index < xlsBook.Sheets.Count -1 . . . . . . . ' here, when you remove Sheets(index), don't increment it ' because next sheet will now have this index. ' NOTE, I am not sure if sheets it 0 or 1-based collection 

事实上,直到你把你的for循环改成while循环,这个问题的确切位置还不清楚。

更新一些来回之后,似乎你需要[在删除之前]添加

 xlsApp.Application.DisplayAlerts = False