将文件保存为xlsx后,工作簿模块中的代码仍会运行

时间:2015-07-11 19:11:39

标签: vb.net vba excel-vba events office-interop

使用VB.NET表单中的按钮,将打开.xlsm文件并将其另存为.xlsx。保存文件后,.xlsx文件(Workbook_BeforeClose事件)中的代码不会被删除,因此,当我想关闭文件时,代码会运行!重新打开文件后,没有任何代码。

这是我的VB.NET类:

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkbooks As Excel.Workbooks

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        xlApp = New Excel.Application
        xlWorkbooks = xlApp.Workbooks
        xlWorkBook = xlWorkbooks.Open("C:\Temp\testTemplate.xlsm")

        xlApp.DisplayAlerts = False
        xlWorkBook.SaveAs(Filename:="C:\Temp\testTemp.xlsx", FileFormat:=51)  '51=xlOpenXMLWorkbook
        xlApp.DisplayAlerts = True

        xlApp.Visible = True

        'Clean Up
        releaseObject(xlWorkBook)
        releaseObject(xlWorkbooks)
        releaseObject(xlApp)
    End Sub

    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
            GC.WaitForPendingFinalizers()
        End Try
    End Sub
End Class

这是在Excel文件,工作簿模块中:

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    MsgBox "event still runs"
End Sub

如何正确保存文件,以便NO代码保留在其中?

1 个答案:

答案 0 :(得分:1)

你是对的,代码在关闭之前不会被删除。我想你可以在xlsm的BeforeClose事件中设置某种类型的标志来检查它的文件类型,只有在它是xlsm时运行。或者您可以执行Worksheets.Copy而不是SaveAs并将生成的工作簿(不包含VBA)保存为xlsx,但可能存在要清理的参考问题。或者您可以设置xlApp.EnableEvents=False,关闭新保存的xlsx,将其重新设置为True并重新打开xlsx。

这是我在第二个选项上写的帖子:http://yoursumbuddy.com/copy-an-xlsm-xlsx/