简体   繁体   中英

Macro that saves the file as macro-free closes the original file

Here is a snippet of the last part of a data manipulation macro:

    Cells.EntireColumn.AutoFit

    Application.ScreenUpdating = True

    Dim fullfilenamelength As Integer, filenamelength As Integer
    fullfilenamelength = Len(ThisWorkbook.FullName)
    filenamelength = Len(udfWBFilename("ThisOne"))

    Dim newFilePath As String, newFileFullName As String
    newFilePath = Left(ThisWorkbook.FullName, fullfilenamelength - filenamelength)
    newFileFullName = newFilePath & "Aspects List.xlsx"

    ActiveWorkbook.SaveAs Filename:=newFileFullName, FileFormat _
        :=xlOpenXMLWorkbook, CreateBackup:=False

    Workbooks.Open Filename:=newFileFullName
    Windows("Aspects List.xlsx").Activate

    Beep
    Application.DisplayAlerts = True
    Application.StatusBar = False
End Sub

Here at the end, it saves the file as a macro-free workbook, then opens the new file.

Why does it close the old file when doing so? (in other words, macro execution is stopped after running the line Windows("Aspects List.xlsx").Activate - the subsequent lines are never executed.)

Just remove this line

Workbooks.Open Filename:=newFileFullName

After performing ActiveWorkbook.SaveAs , your active workbook already refers to Aspects List.xlsx :

Before SaveAs :

在此处输入图片说明

After SaveAs :

在此处输入图片说明

Btw, it seems to me that

newFilePath = Left(ThisWorkbook.FullName, fullfilenamelength - filenamelength)

could be simplified to

newFilePath = ThisWorkbook.Path & "\"

Also it may be interesting: How to avoid using Select/Active statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM