Worksheet save as excel

Содержание

  1. Метод Worksheet.SaveAs (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Поддержка и обратная связь
  6. Workbook.SaveAs method (Excel)
  7. Syntax
  8. Parameters
  9. Remarks
  10. Example
  11. Support and feedback
  12. Worksheet.SaveAs method (Excel)
  13. Syntax
  14. Parameters
  15. Remarks
  16. Support and feedback

Метод Worksheet.SaveAs (Excel)

Сохраняет изменения на диаграмме или листе в другом файле.

Синтаксис

expression. SaveAs (FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AddToMru, TextCodepage, TextVisualLayout, Local)

Выражение Переменная, представляющая объект Worksheet .

Параметры

Имя Обязательный или необязательный Тип данных Описание
FileName Обязательный String Variant. Строка, указывающая имя сохраняемого файла. Можно включить полный путь; В противном случае Microsoft Excel сохранит файл в текущей папке.
FileFormat Необязательный Variant Формат файла, используемый при сохранении файла. Список допустимых вариантов см. в перечислении XlFileFormat . Для существующего файла форматом по умолчанию является последний указанный формат файла; Для нового файла по умолчанию используется формат используемой версии Excel.
Password Необязательный Variant Строка с учетом регистра (не более 15 символов), указывающая пароль защиты, который будет присвоен файлу.
WriteResPassword Необязательный Variant Строка, указывающая пароль резервирования записи для этого файла. Если файл сохраняется с паролем и пароль не предоставляется при открытии файла, он открывается только для чтения.
ReadOnlyRecommended Необязательный Variant Значение true для отображения сообщения при открытии файла, в котором рекомендуется открыть файл только для чтения.
CreateBackup Необязательный Variant Значение True для создания файла резервной копии.
AddToMru Необязательный Variant Значение true , чтобы добавить эту книгу в список недавно использовавшихся файлов. Значение по умолчанию — False.
TextCodepage Необязательный Variant Не используется в Microsoft Excel на английском языке США.
TextVisualLayout Необязательный Variant Не используется в Microsoft Excel на английском языке США.
Local Необязательный Variant Значение True сохраняет файлы на языке Excel (включая параметры панели управления). Значение False (по умолчанию) сохраняет файлы на языке Visual Basic для приложений (VBA) (как правило, на английском языке США, если проект VBA, из которого выполняется Workbooks.Open, не является старым проектом VBA с интернационализацией XL5/95).

Замечания

Используйте надежные пароли, содержащие строчные и прописные буквы, цифры и знаки. В слабых паролях эти элементы не комбинируются. Надежный пароль: Y6dh!et5. Слабый пароль: House27. Используйте надежный пароль, который можно запомнить, чтобы не пришлось его записывать.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Workbook.SaveAs method (Excel)

Saves changes to the workbook in a different file.

Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.

Syntax

expression.SaveAs (FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)

expression A variable that represents a Workbook object.

Parameters

Name Required/Optional Data type Description
FileName Optional Variant A string that indicates the name of the file to be saved. You can include a full path; if you don’t, Microsoft Excel saves the file in the current folder.
FileFormat Optional Variant The file format to use when you save the file. For a list of valid choices, see the XlFileFormat enumeration. For an existing file, the default format is the last file format specified; for a new file, the default is the format of the version of Excel being used.
Password Optional Variant A case-sensitive string (no more than 15 characters) that indicates the protection password to be given to the file.
WriteResPassword Optional Variant A string that indicates the write-reservation password for this file. If a file is saved with the password and the password isn’t supplied when the file is opened, the file is opened as read-only.
ReadOnlyRecommended Optional Variant True to display a message when the file is opened, recommending that the file be opened as read-only.
CreateBackup Optional Variant True to create a backup file.
AccessMode Optional XlSaveAsAccessMode The access mode for the workbook.
ConflictResolution Optional XlSaveConflictResolution An XlSaveConflictResolution value that determines how the method resolves a conflict while saving the workbook. If set to xlUserResolution, the conflict-resolution dialog box is displayed.

If set to xlLocalSessionChanges, the local user’s changes are automatically accepted.

If set to xlOtherSessionChanges, the changes from other sessions are automatically accepted instead of the local user’s changes.

If this argument is omitted, the conflict-resolution dialog box is displayed. AddToMru Optional Variant True to add this workbook to the list of recently used files. The default value is False. TextCodepage Optional Variant Ignored for all languages in Microsoft Excel.

NOTE: When Excel saves a workbook to one of the CSV or text formats, which are specified by using the FileFormat parameter, it uses the code page that corresponds to the language for the system locale in use on the current computer. This system setting is available in the Control Panel > Region and Language > Location tab under Current location. TextVisualLayout Optional Variant Ignored for all languages in Microsoft Excel.

NOTE: When Excel saves a workbook to one of the CSV or text formats, which are specified by using the FileFormat parameter, it saves these formats in logical layout. If left-to-right (LTR) text is embedded within right-to-left (RTL) text in the file, or vice versa, logical layout saves the contents of the file in the correct reading order for all languages in the file without regard to direction. When an application opens the file, each run of LTR or RTL characters are rendered in the correct direction according to the character value ranges within the code page (unless an application that is designed to display the exact memory layout of the file, such as a debugger or editor, is used to open the file). Local Optional Variant True saves files against the language of Microsoft Excel (including control panel settings). False (default) saves files against the language of Visual Basic for Applications (VBA) (which is typically US English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project).

Use strong passwords that combine uppercase and lowercase letters, numbers, and symbols. Weak passwords don’t mix these elements.

  • Strong password: Y6dh!et5
  • Weak password: House27

Use a strong password that you can remember so that you don’t have to write it down.

Example

This example creates a new workbook, prompts the user for a file name, and then saves the workbook.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Worksheet.SaveAs method (Excel)

Saves changes to the chart or worksheet in a different file.

Syntax

expression.SaveAs (FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AddToMru, TextCodepage, TextVisualLayout, Local)

expression A variable that represents a Worksheet object.

Parameters

Name Required/Optional Data type Description
FileName Required String Variant. A string that indicates the name of the file to be saved. You can include a full path; if you don’t, Microsoft Excel saves the file in the current folder.
FileFormat Optional Variant The file format to use when you save the file. For a list of valid choices, see the XlFileFormat enumeration. For an existing file, the default format is the last file format specified; for a new file, the default is the format of the version of Excel being used.
Password Optional Variant A case-sensitive string (no more than 15 characters) that indicates the protection password to be given to the file.
WriteResPassword Optional Variant A string that indicates the write-reservation password for this file. If a file is saved with the password and the password isn’t supplied when the file is opened, the file is opened as read-only.
ReadOnlyRecommended Optional Variant True to display a message when the file is opened, recommending that the file be opened as read-only.
CreateBackup Optional Variant True to create a backup file.
AddToMru Optional Variant True to add this workbook to the list of recently used files. The default value is False.
TextCodepage Optional Variant Not used in U.S. English Microsoft Excel.
TextVisualLayout Optional Variant Not used in U.S. English Microsoft Excel.
Local Optional Variant True saves files against the language of Excel (including control panel settings). False (default) saves files against the language of Visual Basic for Applications (VBA) (which is typically US English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project).

Use strong passwords that combine uppercase and lowercase letters, numbers, and symbols. Weak passwords don’t mix these elements. Strong password: Y6dh!et5. Weak password: House27. Use a strong password that you can remember so that you don’t have to write it down.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Skip to content

VBA Save Sheet as Workbook Excel Macro Code

Home » VBA » VBA Save Sheet as Workbook Excel Macro Code

  • vba save worksheet as workbook

VBA code to save sheet as Workbook example code will help us to save a specific sheet as new workbook. We can use Copy and SaveAs methods of Workbook to copy and save the sheet into new workbook. In this example we will see how to save Active Sheet and specific worksheet as new excel file using VBA. And this code should work for all the version of Microsoft Excel 2003, Excel 2007, Excel 2010, and Excel 2013.

vba save worksheet as workbook

VBA code to save Sheet as New Workbook

Here is the Example VBA syntax and Example VBA code to save a Sheet as New Workbook. This will help you to how to save a worksheet as New Workbook using VBA.

VBA Save Sheet as Workbook: Syntax

Following is the VBA Syntax and sample VBA code to Save a Sheet as Workbook using VBA. We are using the Copy and SaveAs methods of the Excel Workbook object.


WORKBOOK1.SHEETS(“WORKSHEET1).COPY BEFORE:= WORKBOOK2.SHEETS(1)
WORKBOOK. SAVEAS “FILE PATH TO SAVE”

Here workbooks can be ActiveWorkbook, ThisWorkbook or a workbook assigned to an object.
ActiveWorkbook. Workbook1 is your source workbook and Worksheet1 is your sheet to copy. And Workbook2 is the destination sheet and sheets(1) and before key words tells Excel to copy the worksheet before the first sheet of workbook2.

Here you can observe that we are copying the worksheet in the first statement. We are using Copy method of workbook to copy the worksheet. Then we are saving the file in as specific location using SaveAs method of Workbook.

Save Worksheet as New Workbook using VBA: Examples

The following VBA code is to Copy the worksheet into new workbook and Save in a specific folder.

Sub sb_Copy_Save_Worksheet_As_Workbook()
     Dim wb As Workbook
    Set wb = Workbooks.Add
    ThisWorkbook.Sheets("Sheet1").Copy Before:=wb.Sheets(1)
    wb.SaveAs "C:temptest1.xlsx"
End Sub 

Instructions to run the vba code to save a worksheet as new Excel Workbook

Please follow the below steps to execute the vba code to save the worksheet as new excel file.
Step 1: Open any existing Excel workbook
Step 2: Press Alt+F11 – This will open the VBA Editor
Step 3: Insert a code module from then insert menu
Step 4: Copy the above code and paste in the code module which have inserted in the above step
Step 5: Change the code as per your requirement
Step 6: Change the file path as per your testing folder
Step 6: Now press F5 to execute the code

Now you can observe that your worksheet is saved as new Excel workbook in the specified folder.

Explained VBA Code to Save worksheet as new Workbook

‘Starting a procedure to save a worksheet as new workbook
Sub sb_Copy_Save_Worksheet_As_Workbook_C()

‘Declaring a variable as workbook to store the newly creating workbook
Dim wb As Workbook

‘adding a new workbook and seting to wb object
Set wb = Workbooks.Add

‘Copying a worksheet from ThisWorkbook into newly creadted workbook in the above statement
ThisWorkbook.Sheets(“Sheet1”).Copy Before:=wb.Sheets(1)

‘Saving the newly created Excel workbook into required folder with specific workbook name
wb.SaveAs “C:temptest1.xlsx”

‘Ending sub procdure to save a worksheet as new workbook
End Sub

Save Active Sheet as New Workbook using VBA: Examples

The following VBA code is to Copy the active worksheet into new workbook and Save in a specific folder.

Sub sb_Copy_Save_ActiveSheet_As_Workbook()
        Set wb = Workbooks.Add
    ThisWorkbook.Activate
    ActiveSheet.Copy Before:=wb.Sheets(1)
    wb.Activate
    wb.SaveAs "C:temptest3.xlsx"End Sub 
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • VBA code to save Sheet as New Workbook
    • VBA Save Sheet as Workbook: Syntax
    • Save Worksheet as New Workbook using VBA: Examples
      • Instructions to run the vba code to save a worksheet as new Excel Workbook
      • Explained VBA Code to Save worksheet as new Workbook
    • Save Active Sheet as New Workbook using VBA: Examples

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

38 Comments

  1. The code works, however, I like to do a save as rather than to a particular drive that is written into the code. .Can you show me this change please.

  2. renato lacerda
    October 28, 2014 at 1:42 AM — Reply

    Hi.

    Maybe this can help.

    Sub sb_Copy_Save_ActiveSheet_As_Workbook(path As String, file As String)
    Set wb = Workbooks.Add
    ThisWorkbook.Activate
    ActiveSheet.Copy After:=wb.Sheets(wb.Sheets().Count)
    wb.Activate
    If Right(path, 1) = ” Then path = Left(path, Len(path) – 1)
    If MsgBox(“O nome do arquivo está correto? ” & path & ” & file & “.xls”, vbYesNo) = vbYes Then
    wb.SaveAs path & ” & file & “.xls”
    End If

    End Sub
    Sub testemain()
    Call sb_Copy_Save_ActiveSheet_As_Workbook(“c:”, “teste”)
    End Sub

  3. Anil Kumar
    November 3, 2014 at 3:24 PM — Reply

    Hi,

    Thanks a lot but is it possible to paste it in pastespecial in the destination sheet.

    Thank you.

  4. PNRao
    November 3, 2014 at 8:20 PM — Reply

    Hi Anil,
    We can do as follows:
    Sub sb_Copy_Save_ActiveSheet_As_Workbook_PasteSpecial()
    Set wb = Workbooks.Add
    ThisWorkbook.Activate
    ActiveSheet.Copy Before:=wb.Sheets(1)
    wb.Activate
    wb.SaveAs “C:temptest3.xlsx”
    wb.Sheets(1).Cells.Copy
    wb.Sheets(1).Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
    Application.CutCopyMode = False
    wb.Save
    End Sub

    Thanks-PNRao!

  5. Jayant SIngh
    January 29, 2015 at 1:14 PM — Reply

    This is very very helpful. thank you so much for this answer. Just one more litle thing : Can you add a code to delete those extra sheets(except the required sheet) in new workbook ?

  6. PNRao
    February 3, 2015 at 10:08 PM — Reply

    Hi Jayant Singh,

    Here is the Code:

    Sub deletAllSheetExcept()
    For Each sht In ActiveWorkbook.Worksheets
        If sht.Name <> "YourSheetName-WhichYouWantToKeep" Then sht.Delete
    Next
    
    End Sub
    

    Thanks-PNRao!

  7. Adina
    March 11, 2015 at 12:24 AM — Reply

    Hi all,

    I am very new to VBA, could you please tell me how can I activate the macro to save in different worksheet?

  8. Jenna
    April 13, 2015 at 8:24 AM — Reply

    Hi There,

    Thanks this has been really useful, how would I add onto the end of the sub to close the file, as I don’t want it to leave the file open.. just saved down into the drive?

    Also is it at all possible to include a cell reference in the worksheet in the new file name… eg I want to save the new file as a company name and date the report relates to. The date is a cell field in the worksheet.

  9. Jenna
    April 13, 2015 at 8:37 AM — Reply

    Also sorry to be a bother, but I have multiple worksheets in the one file that I am trying to save, however each worksheet is a filtered result but I get an error message saying the copy and paste area is not the same?

    Any advice?

  10. PNRao
    April 13, 2015 at 8:52 PM — Reply

    Hi Jenna,

    Let’s see your second question first:
    You can use the file name from a Cell reference: The below code refers the file path from Range B1 of required sheet:

    Example Case: If B1 value is C:temptest1.xlsx

    Dim strFileName
    strFileName=Sheets("SheetName").Range("B1")
    
    '...... your statements
    wb.SaveAs strFileName
    

    Your Case: If B1 value is date, B2 value is a company name, And B3 value is target folder
    B1=ABCCompany
    B2=12/3/2015
    B3=”C:temp”

    Then the code would be:

    Dim strFileName
    strFileName=Sheets("SheetName").Range("B3") &Sheets("SheetName").Range("B2") &" &Sheets("SheetName").Range("B1") 
    
    '...... your statements
    wb.SaveAs strFileName
    

    Now your first question: you can use the Close method of a workbook to close the file

    '...... your statements
    wb.Close ' to close the file
    

    Thanks-PNRao!

  11. PNRao
    April 13, 2015 at 8:56 PM — Reply

    Do you want to save all three sheets in one workbook, then you can just use wb.SaveAs ‘YourFilePathandName’

    Please describe your issue with more information.

    Thanks-PNRao!

  12. Feroz
    June 11, 2015 at 6:28 PM — Reply

    Hi Sir
    Iam new to VBA coding,i have a problem please help to resolve.

    Problem :
    I have a multiple sheets and sheet names are based on country name.
    I want to create multiple workbooks based on the sheet names in a single run .

    Example : i have 5 sheets with different country name like (Ind,Brazil,china,russia,US)
    i want to create a separate workbook for India ,separate workbook for Brazil..etc) it should be dynamically pick the sheet name and create a workbook.

    Please help to query this issue

  13. Gene
    August 15, 2015 at 6:09 PM — Reply

    I’m trying to have Excel save a file with the contents of a cell (happens to be a date code) but give me the option to edit the file before saving so it would have to display the pop up save as dialog box enter the contents of the specified cell and wait for my further input and to press the save button. Can this be accomplished?

  14. PNRao
    August 16, 2015 at 2:24 AM — Reply

    Hi Gene,
    Yes, we can read the file path and name from a excel range/cell and use VBA and FileDailog to SaveAS with required name. The below macro will wait for user to press Save button to SaveAs with altered file name at desired file ath:

    Sub sbSaveAsExcelDialog()
    
    Dim IntialName As String
    Dim sFileSaveName As Variant
    InitialName = Range("A1") 'Change the cell address as per your requirement
    sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
        fileFilter:="Excel Files (*.xls*), *.xls*") ' You can change the file filters as per your requirement
    
    If fileSaveName <> False Then
        ActiveWorkbook.SaveAs sFileSaveName
    End If
    
    End Sub
    

    Please make sure to format the date to accept as a file name (i.e; if you want to use date as a file name, you have to remove the special characters like: /,:,-)

    Thanks-PNRao!

  15. Gene
    August 18, 2015 at 9:40 AM — Reply

    Thanks! worked like a charm.

  16. PNRao
    August 18, 2015 at 12:50 PM — Reply

    Welcome Gene! I’m glad it worked. Thanks-PNRao

  17. Costas Pap
    September 28, 2015 at 3:06 AM — Reply

    Hallo from me to you all with great skills in programming (my opinion and you can’t change it – sorry!!!)
    I did the code above (excel 2010) but when I save it I can’t see a anything anywhere !!!!
    What am I doing wrong?
    thank you for your time

    Private Sub cbSaveAs_Click()
    Dim IntialName As String
    Dim sFileSaveName As Variant
    InitialName = Range(“B6”).Value & “-” & Range(“B9″).Value ‘it takes the B6-B9 name – its the only code I changed Change the cell address as per your requirement
    sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
    fileFilter:=”Excel Files (*.xls*), *.xls*”) ‘ You can change the file filters as per your requirement

    If fileSaveName False Then
    ActiveWorkbook.SaveAs sFileSaveName
    End If
    End Sub

  18. Costas Pap
    September 28, 2015 at 4:13 AM — Reply

    What I want to do is this:
    Working in workbook with userform with buttons
    So it creates a new sheet with B6 & B9 cell values
    Afterwards with this macro I want to create a new Excel file with the name of B6 cell and transfer in there the sheet with B6 & B9 cells value.
    Just that most of the times the B6 value maybe the same for example:
    sheet like this 8620-112233 and sheet with 8620-998877 these 2 sheets must be stored in a file 8620.xlsx.
    The only thing is that today I create the 1rst sheet and 1 week later I create the 2nd sheet. So I must transfer the 2nd sheet INTO the old file (8620.xlsx) but keep the 1rst sheet in that file and I have to do with a button to be simple.

  19. Costas Pap
    September 28, 2015 at 4:24 AM — Reply

    Else we go to the 1rst solution as above but with the problem I mentioned
    Sorry for making 3 posts

  20. Michael
    October 11, 2015 at 10:55 PM — Reply

    HI,

    You posted this code back in August but I am now looking at this in Oct. I have situation where I need to tweak the following cole with something like this below. How would you tweak the August code with the one that I’m working on now:

    My project is to create a separate sheet from a pivot table where I have the filter on Doctor (I make a sheet for each doctor using the Pivot Table).

    I need to move this sheet from the current workbook to a new file – with the doctors name and billing period The file needs to be named something like “[Doctor’s Name from the sheet from the Pivot Table] – Q3 Billing”. I would also like to make this flexible enough to change the Q3 to another period in the future. this file is going to be reused on a monthly basis so I would like to set it up so it is flexible to accommodate the File name – all at one time (I may have 10-15 doctors in one pivot table for a particular month).

    The code I’m working with now:

    Sub CopySheets()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
    If ws.Name “Master” Then
    ws.Copy
    With ActiveSheet.Cells
    .Copy
    .PasteSpecial xlPasteValues
    End With
    With ActiveWorkbook
    .SaveAs “Drive:Filepath” & ActiveSheet.Range(“A1”).Value & “.Xlsx”, FileFormat:=51
    .Close
    End With
    End If
    Next ws
    End Sub

    The August code you added

    Sub sbSaveAsExcelDialog()

    Dim IntialName As String
    Dim sFileSaveName As Variant
    InitialName = Range(“A1″) ‘Change the cell address as per your requirement
    sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
    fileFilter:=”Excel Files (*.xls*), *.xls*”) ‘ You can change the file filters as per your requirement

    If fileSaveName False Then
    ActiveWorkbook.SaveAs sFileSaveName
    End If

    End Sub

  21. Michael D
    October 12, 2015 at 6:51 AM — Reply

    Going back to August 14, you posted the following code:

    Sub sbSaveAsExcelDialog()

    Dim IntialName As String
    Dim sFileSaveName As Variant
    InitialName = Range(“A1″) ‘Change the cell address as per your requirement
    sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
    fileFilter:=”Excel Files (*.xls*), *.xls*”) ‘ You can change the file filters as per your requirement

    If fileSaveName False Then
    ActiveWorkbook.SaveAs sFileSaveName
    End If

    End Sub

    I’m working on the following code (where I am making a sheet based upon a pivot table then moving it to a new file with the
    Doctor’s name). How do I incorporate this piece (sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, _
    fileFilter:=”Excel Files (*.xls*), *.xls*”) ‘ You can change the file filters as per your requirementinto the follwing code”

    Sub CopySheets()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
    If ws.Name “Master” Then
    ws.Copy
    With ActiveSheet.Cells
    .Copy
    .PasteSpecial xlPasteValues
    End With
    With ActiveWorkbook
    .SaveAs “Drive:Filepath” & ActiveSheet.Range(“A1”).Value & “.Xlsx”, FileFormat:=51
    .Close
    End With
    End If
    Next ws
    End Sub

    Thank you for your help.

  22. Steve
    October 30, 2015 at 8:12 AM — Reply

    Hello
    I am new to this part of excel and was wondering if you could help me.
    Could you show me the code I would need to do the following.
    To save the current WORKBOOK
    To create and save a new workbook with all the sheets copied (Time sheet, Pay sheet, Data, Pay Data, Tax)
    The new workbook name being 14 days after either the current workbook name or “Time sheet”H4
    I would then like the data in the new workbook Time sheet cells C8 to C14, D8 to D14, C17 to C23 and D17 to D23 erased or deleted.
    I would also like the selected option in cells B8 to B14 and B17 to B23 to come up blank(waiting for a selection from the list) or to have the “DAY OFF” selection appear.
    I would like the valve from the current workbook “Time sheet”G28 and “Time sheet”G29 to be linked to the new workbook “Time sheet”C28 and “Time sheet”C29

    Could you help with this. Cheers Steve

  23. char
    January 13, 2016 at 5:45 AM — Reply

    Hi There!

    How do I copy select columns from multiple tabs to a work sheet (same columns in different tabs by month).

  24. Peter Theodorou
    April 16, 2016 at 5:08 PM — Reply

    At 72 years old, I decided to start playing with VBA. I have managed to get a few ‘programs’ working in my XL2007 and need some help with the following. I have an invoicing program that I wrote with the help of information from the net and what I got stuck with now is that I would like to print the resulting Invoice on a PDF file for sending to customer. Considering that I have 8 working sheets on the file and need to only print the one sheet (Invoice). Can you help me overcome this by sending me a code to type in. I will modify file names etc as well as the directory as each customer has he one directory. So the PDF saved will have the customer’s name & Invoice Number & Date. I will be most grateful with any help I can get. Thank you and keep up the great work you are doing. Knowledge must be spread and not limited or controlled by the few.
    Peter Theodorou

  25. Mehul
    June 2, 2016 at 6:24 PM — Reply

    Hello Every one,
    Greetings!
    Please help me on one thing,
    I want to save current worksheet of open workbook
    as new worksheet in the same workbook.
    For example if SheetA is current w.s. then save this sheet
    in the same w.b. with name CopySheetA
    and save this sheet on every 1 or 2 second.

    thanks & rgds

  26. TruVET
    July 6, 2016 at 4:39 PM — Reply

    I have a workbook with 10 sheets I only want to save 3 of the 10 sheets into a file how can i do this?

  27. matthew r
    September 9, 2016 at 2:45 PM — Reply

    Hi.

    I wonder if you can help. I am trying to save a workbook with the data from one of the cells in one of the active worksheets. I have renamed all the sheet no. so I don’t know if this has an effect.

    For example I have 5 active sheets within the workbook let call them RED ONE, GREEN ONE, BLUE ONE, ORANGE ONE, YELLOW ONE.

    Im trying to save the entire workbook into a destination folder using the save name from cell C7 on sheet ‘RED ONE’.

    Heres what I have so far.

    Sub SaveInvWithNewName()
    Dim NewFN As Variant
    ActiveWorkbook.Sheets.Copy
    NewFN = “C:MCM CloudEstimatingQuote NumbersQUOTE_” & Range(“C7”).Value & “.xlsx”
    ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
    ActiveWorkbook.Close
    NEXTINVOICE
    End Sub

    This works apart from it doesnt save new name from cell ‘C7’ on worksheet ‘RED ONE’

    Can you help.

    Regards

    Matt

  28. matthew r
    September 9, 2016 at 2:46 PM — Reply

    Hi.

    I wonder if you can help. I am trying to save a workbook with the data from one of the cells in one of the active worksheets. I have renamed all the sheet no. so I don’t know if this has an effect.

    For example I have 5 active sheets within the workbook let call them RED ONE, GREEN ONE, BLUE ONE, ORANGE ONE, YELLOW ONE.

    Im trying to save the entire workbook into a destination folder using the save name from cell C7 on sheet ‘RED ONE’.

    Heres what I have so far.

    Sub SaveInvWithNewName()
    Dim NewFN As Variant
    ActiveWorkbook.Sheets.Copy
    NewFN = “C:MCM CloudEstimatingQuote NumbersQUOTE_” & Range(“C7”).Value & “.xlsx”
    ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
    ActiveWorkbook.Close
    NEXTINVOICE
    End Sub

    This works apart from it doesnt save new name from cell ‘C7’ on worksheet ‘RED ONE’

    Can you help.

    Regards

    Matt

  29. Rina
    January 18, 2017 at 12:54 PM — Reply

    Hi Ankit,

    I have a list of production Csv files, out of which the month column “B” needs to be changed every month for all the list of files, for which i have created a macro, which amends only colum “B” which is 85 % working files for all the files, except few where apart Column B , even colum “E ” (hold some value) .
    Issue is because , the files are Csv files, if i amend the macro with .xls, it’s 100% working fine. I even tried by converting the Csv files to .xls but still however i could find the value changed files
    Is there any way, i can make sure that except “B” colum , no other column gets changed

  30. Tanzeel
    February 10, 2017 at 1:59 AM — Reply

    Dear Sir(s)

    I have a situation where we sell different varieties of items at different prices to regular customers. the prices vary on a day to day basis and so does the quantity that each customer buys.
    My requirements are that when we input the quantity and rates, we get the amount. i have made 31 work sheets in my masterfile for each date and has the list of all my customers with provision to insert their purchase and the price. Now I want a weekly total of the sales that we have made. I have linked the autosum to a differnt file named weekly report. This i would like to consolidate for monthly and then yearly basis. The problem is that the 31 sheets in my daily log book are finished and so is my weekly data completed for a month. Now i want to know how to write a code so that at the end of each month my daily log book and weekly report is saved by the name of the month at the end automatically and the process of updating each individual month then starts from the master file. Also once the file is saved with a new name will i lose my data that is still linked to the file? Kindly help me please.
    Thanks in advance

  31. Marcin
    February 10, 2017 at 7:48 PM — Reply

    Hi All,
    I would like to assign a macro to a button which when pressed will copy and paste special a sheet into a new workbook. This workbook should get a name which is in a cell C8 of this active sheet. Also I would like to save this file into a folder name which will be in cell C9. Of course there will be a fixed path to this folder. If folder does not exist yet I would like this to be created.
    Can you help me with this?
    Thanks in advance
    Marcin

  32. Jarrod Sandri
    March 13, 2017 at 9:57 AM — Reply

    Hey,

    I want to export one worksheet as a copy of the data that will just open when button (Marco) is pushed. Then I can save where ever i want and whoever uses the workbook can use the same.

    Regards

  33. dear sir

    how to write this plz help me regards given below

    Sub saveinvwithnewname()
    Dim newfn As Variant
    ‘copy invoice to a new workbook
    ActiveSheet.Copy
    newfn = “c:ssinv” & Range(“i5”).Value & “.xlxs”
    ActiveWorkbook.SaveAs newfn, FileFormat:=XlopenXMLWorkbook
    ActiveWorkbook.Close
    nextinvoice
    End Sub

  34. Sot Sreng
    April 9, 2018 at 2:04 PM — Reply

    How code copy two sheet to new workbook?

  35. PNRao
    April 14, 2018 at 10:12 AM — Reply
    Sub sbCopySheetsToNewWorkbook()
    
        Sheets(Array("Sheet2", "Sheet3")).Copy
        
    End Sub
    Sub sbCopySheetsToSpecificWorkbook()
        Sheets(Array("Sheet2", "Sheet3")).Copy Before:=Workbooks("Book3").Sheets(1)
    End Sub
    

  36. April Lancashire
    October 10, 2018 at 7:38 PM — Reply

    Hello,

    Thank you very much for all of the above, it has been really useful for me.

    I have one issue, i need to save the new file as a csv file, how would i do this (forgive me i am a VB newbie)

    So far i have;

    Sub sb_Copy_Save_Worksheet_As_Workbook()
    Dim strFileName
    strFileName = Sheets(“JobCard”).Range(“E3″) & ” & Sheets(“JobCard”).Range(“E5”) & “.” & csv & ”

    Dim wb As Workbook
    Set wb = Workbooks.Add
    ThisWorkbook.Sheets(“csv”).Copy Before:=wb.Sheets(1)
    wb.SaveAs strFileName
    End Sub

    Thanks,
    April

  37. April Lancashire
    October 10, 2018 at 7:41 PM — Reply

    Sorry this is the code i have;

    Sub sb_Copy_Save_Worksheet_As_Workbook()
    Dim strFileName
    strFileName = Sheets(“JobCard”).Range(“E3″) & ” & Sheets(“JobCard”).Range(“E5”)

    Dim wb As Workbook
    Set wb = Workbooks.Add
    ThisWorkbook.Sheets(“csv”).Copy Before:=wb.Sheets(1)
    wb.SaveAs strFileName
    End Sub

  38. Harsh
    September 22, 2020 at 2:18 PM — Reply

    There are multiple sheets from sheet1 to sheet13 in one workbook abc.xlsm (macro language file).The query is need to transfer sheets from sheet 1 to sheet13 into different workbook as sheet1 from abc.xlsm will transfer into r1.xls, sheet2 from abc.xlsm will transfer into r2.xls.

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Сохранение файла рабочей книги Excel, существующего или нового, с помощью кода VBA. Методы Save и SaveAs объекта Workbook, параметр SaveChanges метода Close.

Сохранение существующего файла

Сохранить существующий открытый файл рабочей книги Excel из кода VBA можно несколькими способами. В примерах используется выражение ActiveWorkbook, которое может быть заменено на ThisWorkbook, Workbooks(«ИмяКниги.xlsx»), Workbooks(myFile.Name), где myFile — объектная переменная с присвоенной ссылкой на рабочую книгу Excel.

Простое сохранение файла после внесенных кодом VBA Excel изменений:

Сохранение файла под другим именем (исходная рабочая книга будет автоматически закрыта без сохранения внесенных изменений):

ActiveWorkbook.SaveAs Filename:=«C:ТестоваяНоваяКнига.xlsx»

Сохранить файл рабочей книги можно перед закрытием, используя параметр SaveChanges метода Close со значением True:

ActiveWorkbook.Close SaveChanges:=True

Чтобы закрыть файл без сохранения, используйте параметр SaveChanges метода Close со значением False:

ActiveWorkbook.Close SaveChanges:=False

Сохранение файла под другим именем при закрытии рабочей книги:

ActiveWorkbook.Close SaveChanges:=True, Filename:=«C:ТестоваяНоваяКнига.xlsx»

Если в примерах с методом Close параметр SaveChanges пропустить, будет открыто диалоговое окно с запросом о сохранении файла.

Новая книга сохраняется с указанием полного имени:

Workbooks.Add

ActiveWorkbook.SaveAs Filename:=«C:ТестоваяНоваяКнига.xlsx»

После этого к новой книге можно обращаться по имени: Workbooks ("НоваяКнига.xlsx").

Если не указать полное имя для сохраняемого файла:

Workbooks.Add

ActiveWorkbook.Save

тогда новая книга будет сохранена с именем и в папке по умолчанию, например: Книга1.xlsx, Книга2.xlsx, Книга3.xlsx и т.д. в папке «Документы».


I am trying to save a single worksheet to a new workbook (VBA should create a new workbook).

The code is running and the new workbook is popping up with the needed data and the save as dialogue window also opens but when I select the name and save the file it is no where to be found the the new workbook stays open as (Book1 or whatever auto populates).

I would like for a Save As name to auto populate when the dialogue window opens and have it referencing to two cells (i.e. $A$11, $B$11) in the original workbook.

Here is my VBA:

Option Explicit

Sub SaveConsolidatedDemandData()
    ' Macro2 Macro
    'Dim NameFile As Variant
            'With Worksheets("SO1")
            'NameFile = .Range("M3") & "_" & .Range("C11") & "_" & .Range("B22") & ".xls"
    'End With

    Application.ScreenUpdating = False
    '
    '
        Sheets("Consolidation").Select
        Sheets("Consolidation").Copy
        Application.GetSaveAsFilename


    Application.ScreenUpdating = True

End Sub

TylerH's user avatar

TylerH

20.6k64 gold badges76 silver badges97 bronze badges

asked Jul 26, 2017 at 18:07

MrDoe's user avatar

1

Here is a macro showing/doing what you are asking for. Change the workbook name as well as sheet name as needed:

Sub test()
Dim wb, wbnew As Workbook 
Dim ws As Worksheet
Dim filename As String

Set wb = Workbooks(2)  'Name of the workbook you are copying from
Set ws = wb.Sheets("Sheet1") 'Name of sheet you are copying
filename = ws.Range("A11") & "_" & ws.Range("B11")& ".xlsm"
'adds new workbook
Set wbnew = Workbooks.Add
wb.Activate

'copies sheet to new workbook
    wb.Sheets("Sheet1").Copy Before:=wbnew.Sheets(1)

'Save as dialog box to save as excel file
Application.Dialogs(xlDialogSaveAs).Show filename

wbnew.Close

End Sub

answered Jul 26, 2017 at 20:08

TJYen's user avatar

TJYenTJYen

3435 silver badges13 bronze badges

1

“Save As” is located in the file tab of the worksheet in Excel. Still, there are also some keyboard shortcuts for using it. One is on the Quick Access Toolbar, or we can press F12 and display the save as option or press the keyboard shortcut CTRL+S, which opens the “Save As” dialog box to save the file in the desired format path.

For example, If you add the “Save As” option to your Quick Access Toolbar, you may move aimlessly over the icon to see its keyboard shortcut. e.g., Alt+H keyboard shortcut to open the Home tab.

Save and Save As: Both shortcuts belong to Excel’s “File” class functions. “Save” and “Save As” shortcut keys in Excel save the temporary data in Excel to an Excel file.

“Save” and “Save As” Shortcuts in ExcelAn Excel shortcut is a technique of performing a manual task in a quicker way.read more are the most important functions as they enable the user to save the data created in Excel. Without these functions, the user may lose the data that has been made in Excel once the file is closed. So, one must understand these functions clearly.

  • The “Save As” shortcut key in Excel differs from the “Save” shortcut in Excel. The “Save As” function enables users to store the data in a separate file or even in an independent format from the original structure.
  • It was introduced when it observed that the user loses the original file once the changes are saved in the file. The “Save As” shortcut function in Excel enables users to save the changes made in the primary file in a new file. Using the “Save As” function, the user can keep the file in the same format, with a different name, or even at a different location.
  • So, Excel’s “Save As” shortcut function offers more functionality than Excel’s traditional “Save” function.
Table of contents
  • Excel Shortcut: “Save As”
    • Save As Shortcut in Excel Examples
    • How to Use the “Save As” Shortcut in Excel?
    • Method #1 – Using the Excel Keyboard Shortcut for “Save As”
    • Method #2 – Add the “Save As” Function to the Quick Access Toolbar in Excel
    • Method #3 – Adding “Save As” Option to the Ribbon in Excel
    • Method #4 – Use VBA as a “Save As” Shortcut
    • Explanation of “Save As” Function in Excel
    • Things to Remember About “Save As” Shortcut in Excel
    • Recommended Articles

Save As Shortcut in Excel Examples

Add the “Save As” function to the ribbon.

  1. Using the “Save As” shortcut key in Excel – F12

    shortcut key example 1

  2. Add the “Save As” function to the Quick Access Toolbar.

    shortcut key example 1-1

  3. Add the “Save As” function to the ribbon.

    shortcut key example 1-2

  4. Using VBA

    shortcut key example 1-3

How to Use the “Save As” Shortcut in Excel?

Below are the four methods of using Excel’s “Save As” shortcut.

Method #1 – Using the Excel Keyboard Shortcut for “Save As”

Step 1 – Make sure that no undoing of actions is required.

Before saving the file, one should ensure that no action performed needs an undo. If it requires undoing, one must first undo the action and then only can save the changes.

Step 2 – Use the keyboard Excel shortcut key “F12” to open the “Save As” dialog box.

Step 3 – Please choose a new file name, type, and location where you want to save the file.

Keyboard key method 1

Method #2 – Add the “Save As” Function to the Quick Access Toolbar in Excel

Step 1

Go to the Quick Access ToolbarQuick Access Toolbar (QAT) is a toolbar in Excel that may be customized and is located on the upper left-hand side of the window. It enables users to save important shortcuts and easily access them when needed.read more and click on the little “dropdown” key.

Save as quick access method 2

Step 2

From the options, choose the option “More Commands.”

Save as quick access method 2-1

Step 3

Choose “All Commands” from the menu and add the “Save As” function to the Quick Access Toolbar.

Save as quick access method 2-2

Step 4

After adding the “Save As” function, we can use it with a single click.

quick access method 2-3

Method #3 – Adding “Save As” Option to the Ribbon in Excel

One can also add the “Save As” function to the ribbon.

Step 1

Click on “File” and choose “Options” from the menu.

ribbon method 3

Step 2

Choose all commands from the customize ribbon tab, search for the “Save As” function, and add that to the ribbon.

ribbon method 3-1

Step 3

After the “Save As” function is added to the ribbon, it will appear below.

method 3-2

Method #4 – Use VBA as a “Save As” Shortcut

VBA can also be used as a shortcut for “Save As” by using the code.

Use VBA method 4

Activeworkbook means active Excel.

Save As is the “Save As” function that must be executed.

“Save this as this name” and enter the name by which the file has to be saved.

Explanation of the “Save As” Function in Excel

Whenever we work on a spreadsheet shared between teammates, then it becomes essential that the other team members should not edit the primary file. For example, suppose there is a situation where the team manager has created a file and shared the file with the teammates. Some teammates have altered the formulas as per their needs and saved the changes in the file.

In such a situation, it will create a problem for the user who has made the primary file, as the teammate’s changes are already saved in the same file. Furthermore, restoring the changes and recovering the original file is impossible. So, to take care of both situations, we use Excel’s “Save As” function to save the changes and keep the primary file.

  • Excel’s “Save As” function allows the user to save the changes by a new file name and enables the user to change the file type and location where the file has been saved.
  • Using the “Save As” function, the user can create the file with a new location and a new file type. However, sometimes the user needs to save a file as a “PDF,” and sometimes they must change the file type to a macro-enabled worksheet. Therefore, it becomes essential that the user has some inbuilt option in such cases. Hence, we have the “Save As” function in Excel.
  • So, whenever we want to save the changes and the primary file, use the “Save As” function. There are many ways to add shortcuts for the “Save As” function.
  • We can use the keyboard shortcut key combinations and add these “Save As” functions in the ribbon or the quick access toolbar. Using the “Save As” shortcut key will enable a user to reduce the time saving the file with conventional methods. Moreover, we also have the VBA code that one can easily use to execute the “Save As” shortcut key in Excel.

Things to Remember About “Save As” Shortcut in Excel

  • We must enter a unique name when using the “Save As” shortcut in Excel. Otherwise, we will get a warning message that “filename exists,” If we accidentally override the warning and hit the save button, the old file will get replaced. Hence, we will lose the primary file.
  • If we used VBA code in ExcelVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more, we must use the Excel extensionExcel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more “.xlsm” while using the “Save As” shortcut in Excel.
  • If we want to save the file with the same name as the primary file, we should change the file’s location while doing the “Save As” shortcut in Excel.

Recommended Articles

This article is a guide to Save As Shortcut in Excel. Here we discuss the keyboard shortcut of Save and Save As, including 4 different Excel methods (the F12 function, using the quick access toolbar, adding it in ribbon, and creating a shortcut in VBA). You may learn more about Excel from the following articles: –

  • Age Calculation in Excel
  • Using a Shortcut key to Merge Cells in Excel
  • Compare Two Excel Columns
  • Unmerge Cells in Excel

Like this post? Please share to your friends:
  • Worksheet object in word
  • Working with data validation in excel
  • Working with columns in word
  • Working well with others word
  • Working out word meaning from context