如何使用Visual Basic代码从文件夹中删除Excel文件?

所以我有一个程序,我通过Visual Studio 2015使用Visual Basic创build。基于窗体…我打开Excel文件,提取数据,重新保存新的数据。 但我不知道如何删除Excel文件….

以下是一些代码示例:

(打开一个空白模板):

oExcel = CreateObject("Excel.Application") oBook = oExcel.Workbooks.Open("File location") 

(修改现有的Excel文件的数据)

  'open the existing excel file oExcel = CreateObject("Excel.Application") oBook = oExcel.Workbooks.Open("c:\Images\" + qcComboBox.Text + ".xlsx") 

所以一旦我完成了Excel文件,我该如何永久删除它?

无论您如何访问Excel文档,它仍然是文件系统中的文档。 就这样删除你的Excel文件

 System.IO.File.Delete(filename) 

如果您已经尝试过System.IO.File.Delete而没有运行,也许您在完成对Excel文档的引用(通常的错误)时没有正确地清理它。 它是一个COM对象,不像CLRpipe理的.NET对象那样由CLRpipe理。 这是你如何做到这一点。 引用COM >> Microsoft Excel 15.0 Object Library (或其他版本)。 并使用这种方法。

 Dim filename = "C:\Users\Public\Documents\test.xlsx" Dim oExcel As New Microsoft.Office.Interop.Excel.Application() ' The next line is necessary because you don't want to make a reference ' to an unmanaged object two levels deep from an existing unmanaged object. ' Otherwise you won't be able to clean it up properly Dim oBooks = oExcel.Workbooks ' don't do it this way, as described above ' Dim oBook = oExcel.Workbooks.Open(filename) Dim oBook = oBooks.Open(filename) ' close your objects, should be enough in most cases oBook.Close() oBooks.Close() oExcel.Quit() ' should not need this but it's an added layer to ensure the objects aren't referenced to System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook) System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks) System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel) ' delete as usual System.IO.File.Delete(filename)