How to use VBA SaveAs without closing calling workbook?

后端 未结 5 565
谎友^
谎友^ 2020-11-27 23:44

I want to:

  • Do data manipulation using a Template workbook
  • Save a copy of this work book as .xlsx (SaveCopyAs doesn\'t let you change filetypes, otherw
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 00:06

    There is nothing pretty or nice about this process in Excel VBA, but something like the below. This code doesn't handle errors very well, is ugly, but should work.

    We copy the workbook, open and resave the copy, then delete the copy. The temporary copy is stored in your local temp directory, and deleted from there as well.

    Option Explicit
    
    Private Declare Function GetTempPath Lib "kernel32" _
             Alias "GetTempPathA" (ByVal nBufferLength As Long, _
             ByVal lpBuffer As String) As Long
    
    Public Sub SaveCopyAs(TargetBook As Workbook, Filename, FileFormat, CreateBackup)
      Dim sTempPath As String * 512
      Dim lPathLength As Long
      Dim sFileName As String
      Dim TempBook As Workbook
      Dim bOldDisplayAlerts As Boolean
      bOldDisplayAlerts = Application.DisplayAlerts
      Application.DisplayAlerts = False
    
      lPathLength = GetTempPath(512, sTempPath)
      sFileName = Left$(sTempPath, lPathLength) & "tempDelete_" & TargetBook.Name
    
      TargetBook.SaveCopyAs sFileName
    
      Set TempBook = Application.Workbooks.Open(sFileName)
      TempBook.SaveAs Filename, FileFormat, CreateBackup:=CreateBackup
      TempBook.Close False
    
      Kill sFileName
      Application.DisplayAlerts = bOldDisplayAlerts
    End Sub
    

提交回复
热议问题