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

时间:2017-03-10 19:20:53

标签: excel vb.net vba visual-studio-2015

所以我有一个程序,我通过Visual Studio 2015使用Visual Basic创建。基于表单...我打开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文件,如何永久删除它?

1 个答案:

答案 0 :(得分:2)

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

System.IO.File.Delete(filename)

如果您在没有运气的情况下尝试过System.IO.File.Delete,那么当您完成它时,您可能无法正确清理对Excel文档的引用(常见错误)。它是一个COM对象,与普通的托管.NET对象不同,它不受CLR管理。以下是如何做到这一点的。引用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)