Vba excel сохранить файл в папку

 

evgeniy_m

Пользователь

Сообщений: 109
Регистрация: 07.07.2014

#1

01.09.2014 23:36:22

Всем доброе время суток! Есть макрос, после обработки которого вылетает окно с сохранением (имя файла берется автоматически с ячейки «А31» ;) :

Код
Имя_для_сохранения = [A31]
    FName = Application.GetSaveAsFilename(InitialFileName:=Имя_для_сохранения, _
                                          FileFilter:="Excel Files (*.xls), *.xls", _
                                          Title:="Выберите имя файла для сохранения")
    If VarType(FName) <> vbBoolean Then ThisWorkbook.SaveAs FName

НО..
как переписать макрос, чтобы файл сохранялся автоматически (без подтверждения кнопки: «Сохранить» ;)  в папку откуда открыт файл?
Заранее спасибо.

 

k61

Пользователь

Сообщений: 2441
Регистрация: 21.12.2012

#2

02.09.2014 02:26:10

Код
sub ggg()
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "" & [A31].Value & ".xls"
end sub
 

evgeniy_m

Пользователь

Сообщений: 109
Регистрация: 07.07.2014

 

socha

Пользователь

Сообщений: 13
Регистрация: 05.10.2014

Здравствуйте.
К продолжению эмой темы.
Надобно сохранить файл под именем ячейки А1, но и папка сохранения должна выбираться автоматически по ячейки А1. То есть путь сохранения C:Заказы «Имя конечной папки А1» «названия файла А1.xls.
Спасибо

 

Sanja

Пользователь

Сообщений: 14838
Регистрация: 10.01.2013

#5

05.10.2014 17:23:12

socha пишет:

Цитата
сохранить файл под именем ячейки А1, и папка сохранения должна выбираться автоматически по ячейки А1

Так это-ж ещё проще

Код
ActiveWorkbook.SaveAs Filename:=[A1].Value & ".xls" 

Согласие есть продукт при полном непротивлении сторон.

 

socha

Пользователь

Сообщений: 13
Регистрация: 05.10.2014

В оригинале у меня место сохранения файла C:РаботаПродажаКлиентыА1″Папка клиента, имя которой совпадает с ячейкой А1.
Но в этой ячейке я указываю не весь путь, а только имя последней папки.  
Спасибо

 

Sanja

Пользователь

Сообщений: 14838
Регистрация: 10.01.2013

#7

05.10.2014 17:37:42

Цитата
socha пишет: в этой ячейке я указываю…имя последней папки

а имя файла где указываете? Тоже в это-же ячейке (см пост #4)?

Согласие есть продукт при полном непротивлении сторон.

 

socha

Пользователь

Сообщений: 13
Регистрация: 05.10.2014

#8

05.10.2014 17:46:10

Вот по такому примеру нужно сделать макрос. Подставил свои параметры — все работает, только место сохранения, тоже должно быть переменное по указаной ячейке

Код
Sub Макрос1() 
Dim a$, d$ 
a = Cells(1, 1) 'a1 name 
d = Cells(2, 1) 'a2 data 
ActiveWorkbook.SaveAs Filename:= _ 
"C:" & a & d & ".xls" 
End Sub

Спасибо

 

Sanja

Пользователь

Сообщений: 14838
Регистрация: 10.01.2013

#9

05.10.2014 17:51:45

Вы же практически все сделали

Код
ActiveWorkbook.SaveAs Filename:="C:" & a & "" & d &  ".xls" 

Согласие есть продукт при полном непротивлении сторон.

 

socha

Пользователь

Сообщений: 13
Регистрация: 05.10.2014

Спасибо, все заработало. Просто не мог разобраться с синтаксисом

 

vlasssov71

Пользователь

Сообщений: 13
Регистрация: 23.09.2014

#11

05.10.2014 19:52:33

Еще символы надо убрать, которые в имени файла нежелательны

Код
Public Function УбратьСимволыИмяФайла(s)

s = Replace(s, ".", "_")
s = Replace(s, "/", "_")
s = Replace(s, "", "_")
s = Replace(s, Chr(34), "_")

УбратьСимволыИмяФайла = s

End Function 
 

athe

Пользователь

Сообщений: 15
Регистрация: 18.06.2015

#12

19.06.2015 10:38:54

Добрый день.
Вижу что тема не очень свежая, но авось…)
Использую формулу товарища k61 (спасибо ему большое):

Код
sub ggg()
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "" & [A31].Value & ".xls"
end sub

К сожалению есть одно неудобство, данный код делает копию файла с указанным в ячейке названием и переходит в эту копию, закрывая изначальный файл. Может есть  у кого код, который делал бы копию файла, не открывая его и не закрывал бы первичный файл?
Заранее благодарен.
С ув. athe.

Изменено: athe19.06.2015 10:41:32

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#13

19.06.2015 10:49:13

Код
ActiveWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & "" & [A31].Value & ".xls"

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

athe

Пользователь

Сообщений: 15
Регистрация: 18.06.2015

The_Prist
Большое спасибо.
Стыд мне и позор… Пошёл дальше читать Слепцову)).

 

RNEtidi

Пользователь

Сообщений: 12
Регистрация: 12.04.2016

#15

12.04.2016 15:58:04

Цитата
The_Prist написал:
19 Июн 2015 10:49:13

Код
ActiveWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & "" & [A31].Value & ".xls"
Код
ThisWorkbook.SaveCopyAs "C:Folder" & NewName

в цикле For..Next выдает ошибку:
Run-time error ‘-2147417848 (80010108)’:
Automation error
The object invoked has disconnected from its clients.

Имя файла NewName изменяется в цикле:

Код
NewName = "Saved_" & x & ".xlsm" 'x - изменяемый циклом параметр

В чем причина может быть? (DoEvents — не помогает).

Изменено: RNEtidi12.04.2016 16:37:05

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

RNEtidi, зачем цитируете всё подряд? Даже подпись. На чём хотели сделать акцент? Кнопка цитирования не для ответа.
И код следует оформлять соответствующим тегом — видели, как у других это выглядит? Ищите такую кнопку и исправьте своё сообщение в части цитаты и оформления. Спасибо!

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#17

12.04.2016 16:36:25

Цитата
RNEtidi написал: В чем причина может быть?

— да хоть в том, что уже выше озвучивалось — в недопустимом имени файла.

 

RNEtidi

Пользователь

Сообщений: 12
Регистрация: 12.04.2016

Hugo

, в моем случае в чем недопустимость имени файла?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Никто не видит, что у Вас в ячейке, из которой берётся имя файла )) Чему равна переменная х?

 

RNEtidi

Пользователь

Сообщений: 12
Регистрация: 12.04.2016

#20

12.04.2016 17:00:09

Код
For x=1 to n 'n - берется из текстбокса формы: n = Val(Textbox1.Text)
NewName = "Saved_" & x & ".xlsm" 'x - изменяемый циклом параметр
DoEvents
ThisWorkbook.SaveCopyAs "C:Folder" & NewName
Next x

x — изменяемый циклом параметр

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#21

12.04.2016 17:17:29

Цитата
Юрий М написал: Чему равна переменная х?
 

RNEtidi

Пользователь

Сообщений: 12
Регистрация: 12.04.2016

ну для начала x = 1. Потом x = 2. И так далее до n. К примеру n = 5, тогда x изменяется от 1 до 5. Цикл For..Next так работает.

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

Сорри, подслеповат вероятно… :)
Тогда должно работать без ошибок, если запись в каталог разрешена.

 

RNEtidi

Пользователь

Сообщений: 12
Регистрация: 12.04.2016

запись в каталог не запрещена, но ошибка все равно выскакивает.

 

Фродо

Пользователь

Сообщений: 348
Регистрация: 10.03.2016

#25

12.04.2016 19:16:43

Цитата
RNEtidi написал:
но ошибка все равно выскакивает.

уникальность имени?

у меня простая версия Экселя, в ней нет кнопки «Прочитать мысли и сгенерировать файл пример»

 

RNEtidi

Пользователь

Сообщений: 12
Регистрация: 12.04.2016

#26

12.04.2016 19:18:37

Цитата
RNEtidi написал:
Run-time error ‘-2147417848 (80010108)’:
Automation error
The object invoked has disconnected from its clients.
 

Фродо

Пользователь

Сообщений: 348
Регистрация: 10.03.2016

#27

12.04.2016 19:23:15

для начало попробуйте все убрать.

Код
ThisWorkbook.SaveCopyAs "C:Folder" & "Saved_" & 1 & ".xlsm"

у меня простая версия Экселя, в ней нет кнопки «Прочитать мысли и сгенерировать файл пример»

 

RNEtidi

Пользователь

Сообщений: 12
Регистрация: 12.04.2016

в этом то вся и прелесть: вне цикла все хорошо сохраняет. а в теле цикла при попытке сохранить выскакивает вышеназванная ошибка и excel напрочь зависает.

 

Фродо

Пользователь

Сообщений: 348
Регистрация: 10.03.2016

#29

12.04.2016 20:02:38

Код
ThisWorkbook.SaveCopyAs "C:Folder" & NewName true

а так попробуйте

файл пример сделайте

у меня простая версия Экселя, в ней нет кнопки «Прочитать мысли и сгенерировать файл пример»

 

RNEtidi

Пользователь

Сообщений: 12
Регистрация: 12.04.2016

#30

12.04.2016 21:49:14

для чего писать true после имени файла?
пример прикрепил. Одну копию сохраняет, а на второй выдает ошибку.

Прикрепленные файлы

  • Example.xlsm (17.4 КБ)

Изменено: RNEtidi12.04.2016 22:35:42
(Перезалил файл. Новый файл пишет log)

In this Article

  • Save Workbook – VBA
    • Save a Specified Workbook
    • Save the Active Workbook
  • VBA Coding Made Easy
    • Save the Workbook Where the Code is Stored
    • Save all Open Workbooks
    • Save all open workbooks that were not opened ReadOnly
    • Save a workbook defined by a variable
    • Save a workbook defined by a string variable
    • Save a workbook defined by the order it was opened.
    • Save a workbook based on a cell value
  • Save As – VBA
    • SaveAs Syntax:
    • Save As Syntax Examples:
    • Workbook Save As – Same Directory
    • Workbook Save As – New Directory
    • Workbook Save As – New Directory, Specify File Extension
    • Workbook Save As – New Directory, Specify File Extension – Alt Method
    • Workbook Save As – Add Password to Open File
    • Workbook Save As – Add Password for Write Privileges
    • Workbook Save As – Read-Only Recommended
  • Other Save As Examples
    • Create Save As Dialog Box
    • Create Save As Dialog Box with Default File Name Provided
    • Create Save As Dialog Box with Default File Name Provided
    • Create & Save New Workbook
    • Disable Save Alerts

This VBA Tutorial covers how to save a file using the Save and Save As commands in VBA.

Save Workbook – VBA

The VBA Save command saves an Excel file similarly to clicking the Save icon or using the Save Shortcut (CTRL + S).

Save a Specified Workbook

To save a workbook, reference the workbook object and use the Save command.

Workbooks("savefile.xlsm").Save

Save the Active Workbook

Note: This is the current active workbook from with in the VBA code, which is different from ThisWorkbook which contains the running code.

ActiveWorkbook.Save

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

vba save as

Learn More!

Save the Workbook Where the Code is Stored

ThisWorkbook.save

Save all Open Workbooks

This will loop through all open workbooks, saving each one.

Dim wb as workbook

For Each wb In Application.Workbooks
	wb.Save
Next wb

Save all open workbooks that were not opened ReadOnly

Note: opening a workbook in ReadOnly mode prevents the file from being saved.
To save the file you will need to use Save As and save the file with a different name.

Dim wb as workbook

For Each wb In Application.Workbooks
	If not wb.ReadOnly then
		wb.Save
	End if
Next wb

Save a workbook defined by a variable

This will save a workbook that was assigned to a workbook object variable.

Dim wb as workbook

set wb = workbooks("savefile.xlsm")
wb.save

Save a workbook defined by a string variable

This will save a workbook that’s name was saved to a string variable.

Dim wbstring as string

wbstring = "savefile.xlsm"
workbooks(wbstring).save

Save a workbook defined by the order it was opened.

Note: The first workbook opened would have 1, the second 2, etc.

workbooks(1).save

VBA Programming | Code Generator does work for you!

Save a workbook based on a cell value

This will save a workbook that’s name is found in a cell value.

Dim wbstring as string

wbstring = activeworkbook.sheets("sheet1").range("wb_save").value
workbooks(wbstring).save

Save As – VBA

The VBA Save As command saves an Excel file as a new file, similar to clicking the Save As icon or using the Save As Shortcut (Alt > F > A).
Above, we identified all the ways to specify which workbook to save. You can use those exact same methods to identify workbooks when using Save As.

Save As behaves similarly to Save, except you also need to specify the name of the new file.
In fact, Save As has many potential variables to define:

SaveAs Syntax:

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

A full description of all of the SaveAs arguments is included below. For now we will focus on the most common examples.
Note: These arguments can be entered as string with parenthesis or as defined variables.

Save As Syntax Examples:

Workbook Save As – Same Directory

ActiveWorkbook.SaveAs Filename:= "new"

or

ActiveWorkbook.SaveAs "new"

or

Dim wbstring as string

wbstring = "new"
ActiveWorkbook.SaveAs Filename:= wbstring

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Workbook Save As – New Directory

ActiveWorkbook.SaveAs Filename:= "C:new"

or

Dim wbstring as string

wbstring = "C:new"
ActiveWorkbook.SaveAs Filename:= wbstring=

Workbook Save As – New Directory, Specify File Extension

ActiveWorkbook.SaveAs Filename:= "C:new.xlsx"

or

Dim wbstring as string

wbstring = "C:new.xlsx"
ActiveWorkbook.SaveAs Filename:= wbstring

Workbook Save As – New Directory, Specify File Extension – Alt Method

You can also specify the file format in it’s own argument.

.xlsx = 51 '(52 for Mac)
.xlsm = 52 '(53 for Mac)
.xlsb = 50 '(51 for Mac)
.xls = 56 '(57 for Mac)
ActiveWorkbook.SaveAs Filename:= "C:new", FileFormat:= 51

Workbook Save As – Add Password to Open File

ActiveWorkbook.SaveAs Filename:= "C:new.xlsx", Password:= "password"

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Workbook Save As – Add Password for Write Privileges

If correct password is not supplied then workbook opens as Read-Only

ActiveWorkbook.SaveAs Filename:= "C:new.xlsx", WriteRes:= "password"

Workbook Save As – Read-Only Recommended

TRUE to display a message box, recommending that the file is opened read-only.

ActiveWorkbook.SaveAs Filename:= "C:new.xlsx", ReadOnlyRecommended:= TRUE

Other Save As Examples

Create Save As Dialog Box

This Generates the Save As Dialog Box, prompting the user to Save the file.
Keep in mind that this simple code may not be appropriate in all cases.

Application.GetSaveAsFilename

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Create Save As Dialog Box with Default File Name Provided

Application.GetSaveAsFilename InitialFilename:="test.xlsx"

Create Save As Dialog Box with Default File Name Provided

Application.GetSaveAsFilename InitialFilename:="test.xlsx"

Create & Save New Workbook

This will create a new workbook and immediately save it.

Dim wb As Workbook

Set wb = Workbooks.Add
Application.DisplayAlerts = False
wb.SaveAs Filename:=”c:Test1.xlsx”
Application.DisplayAlerts = True

Disable Save Alerts

As you work with saving in VBA, you may come across various Save Warnings or Prompts. To disable warnings, add this line of code:

Application.DisplayAlerts=False

and to re-able alerts:

Application.DisplayAlerts=True
Skip to content

Save Workbook Using Excel VBA to Specific Folder

Home » Excel VBA » Save Workbook Using Excel VBA to Specific Folder

  • SaveAs dialogbox

VBA save as Workbook Excel Macro code helps Save file to a specific Folder, its is a common task in automation process. Once you are done with actual calculations or task, at end of the procedure we generally call a procedure to export or Save the Output File to a Specific Folder or common drive. Or in other case you may not have the permissions to Save the File in a location, so that you can use SaveAs Option to store the revised or updated file.

VBA save as Workbook – Solution(s):

Save Workbook Using Excel VBA to Specific Folder You can use SaveAs method to Save the File to a specific location. You can Save with the same File Name and Location. Or you can use different File Name and Location to Save the File. You can also set to an object and Save the File.

In other method, you use Save Dialog Box. So that user can choose a specific folder to save the Excel File.

Save Workbook to Specific Folder – Example Cases:

  • Save Workbook to Specific Folder
  • Set to an Object and Save it
  • Save Workbook to Specific Folder using Save Dialog Box
  • Save Workbook in the same location of the Macro (this) Workbook
  • Save the Workbook
  • Download: Example Macro Workbook
Save a Workbook to a Specific Folder

The following example show you how to save an Excel Workbook in Specific folder using SaveAs method:

Sub ExampleToSaveWorkbook()

Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs "C:WorkbookName.xls"
'OR
'ActiveWorkbook.SaveAs Filename:="C:WorkbookName1.xls"

End Sub
Set to an Object and Save it

Set to an Object and Save it, so that it is easy to refer to your workbook to do further tasks. If you are dealing with more than one workbook, you will need this method to access a specific Excel Workbook.

Sub ExampleToSaveWorkbookSet()

Dim wkb As Workbook
'Adding New Workbook
Set wkb = Workbooks.Add
'Saving the Workbook
wkb.SaveAs "C:WorkbookName.xls"
'OR
'wkb.SaveAs Filename:="C:WorkbookName1.xls"

End Sub
Save Workbook to Specific Folder using Save Dialog Box

You can Save the Workbook to Specific Folder by showing the Save Dialog Box to user. So that user can choose desired location to save the file.

SaveAs dialogbox

Sub sbSaveExcelDialog()

Dim IntialName As String
Dim sFileSaveName As Variant
IntialName = "Sample Output"
sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, fileFilter:="Excel Files (*.xlsm), *.xlsm")

If sFileSaveName <> False Then
    ActiveWorkbook.SaveAs sFileSaveName
End If

End Sub

Save Workbook in the same location of the Macro (this) Workbook

You can save the workbook in the same directory of the macro workbook using ThisWorkbook.Path property.

Sub ExampleToSaveWithSamePathDifferentName()
Dim sFilename As String
sFilename = "WorkbookName.xls" 'You can give a nem to save

Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs ThisWorkbook.Path & "" & sFilename

End Sub

Save the Workbook

You can simply save the file without changing its file name or path name using Save method.

Sub ExampleToSaveWithSameNameandPath()

'Saving the Workbook
ActiveWorkbook.Save

End Sub
Example Files

You can download the example file and explore it.
ANALYSISTABS – Save Workbook

Overwrite an Existing Workbook using VBA

While Saving the existing workbook or a new excel file with existing name, Excel will prompt a warning message. It will interrupt the procedure and ask user to press yes or no for overwriting a file.

Overwrite an Existing Workbook using VBA – Solution:

Overwrite an Existing Workbook in Excel VBA
You can avoid this by disabling the alerts temporarily and save the workbook with the same name by setting the Application.DisplayAlerts=False property. Once you are done with the task, you should enable the application alerts by setting the property TRUE.

Overwrite an Existing Workbook using VBA – An Example

The following example will show you, how to overwrite a file by disabling the application alerts.

Code:
sub procedure to over write an excel file
Sub ExampleToOverWriteExistingWorkbook()
'Declaration: Declaring the variable
Dim wkb As Workbook

'Adding New Workbook using Workbook.Add method and setting to wkb Object
Set wkb = Workbooks.Add

'Saving the Workbook

'Desable the application alerts before svaing the file
Application.DisplayAlerts = False

'Now save the file
wkb.SaveAs "C:WorkbookName.xls" ' change to existng file name
'OR
'wkb.SaveAs Filename:="C:WorkbookName1.xls"</span>

'Eanbling the Application Aletrts after saving the file
Application.DisplayAlerts = True

End Sub
Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Insert a Module for Insert Menu
  4. Copy the above code and Paste in the code window
  5. Save the file as macro enabled workbook
  6. Press F5 to execute itit
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 save as Workbook – Solution(s):
  • Save Workbook to Specific Folder – Example Cases:
    • Overwrite an Existing Workbook using VBA
    • Overwrite an Existing Workbook using VBA – Solution:

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:

28 Comments

  1. Katharina
    February 3, 2014 at 9:22 AM — Reply

    Your means of describing all in this paragraph is really good,
    every one be able to easily understand it, Thanks a
    lot.

  2. PNRao
    February 3, 2014 at 9:54 AM — Reply
  3. Rob
    October 15, 2014 at 5:30 AM — Reply

    Having trouble using the below code. Any ideas?
    SaveFile = Application.GetSaveAsFilename( _
    FileFilter:=”Excel Files (*.xlsx), *.xlsx”)
    ActiveWorkbook.SaveAs SaveFile

    After the file is saved it appears as an Excel file in the indicated location, but when you try to open it a dialogue box says: “Excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.”

  4. PNRao
    October 18, 2014 at 1:57 PM — Reply

    Hi Rob,
    I found no issues in your code, you may be using Excel 2003. If your Excel is not 2007 or higher, you can change the “Excel Files (*.xlsx), *.xlsx” as “Excel Files (*.xls), *.xls”

    i.e; xls, instead of xlsx

    Thanks-PNRao!

  5. Hi. This is great help thanks! But I am trying to combine two codes but I cannot do it! I would like the macro to save the workbook as a file name taken from a cell and also save in in a certain folder location.! Please can you help?!!

  6. PNRao
    November 29, 2014 at 7:44 PM — Reply

    Hi Jason,
    Assuming you have the Folder path at Range A1 of sheet1, and File name at Range A2:

    wkb.SaveAs Filename:=Sheets(“Sheet1”).Range(“A1″) &” &Sheets(“Sheet1”).Range(“A2″) &”.xlsx”

    Hope this helps!
    Thanks-PNRao!

  7. Chris
    January 7, 2015 at 3:02 AM — Reply

    Hi,
    Can I use a macro to save the excel file in a specific location based off of a specific cell within the document? Also, Could I have the macro change the name of the document based off of a different cell within the same document?

  8. PNRao
    January 12, 2015 at 9:38 PM — Reply

    Hi Chris,

    Yes, you can use SaveAs method of workbook to save the file with different name. Assuming you have the file name in the Cell A1.

    The below code will save the active workbook in the same path with name specified at A1.

    Dim strFilename As String
    strFilename = ActiveWorkbook.Path & " & Range("A1") & ".xlsm"
    ActiveWorkbook.SaveAs Filename:=strFilename, FileFormat:=52
    

    The below code will save the active workbook in the given path with file name mentioned with the full path at A1.

    Dim strFilename As String
    strFilename =Range("A1") & ".xlsm"
    ActiveWorkbook.SaveAs Filename:=strFilename, FileFormat:=52
    

    Thanks-PNRao!

  9. mo
    March 25, 2015 at 6:04 PM — Reply

    hi,

    i am trying to use this code but having some issues,

    i am using excel 2010 but the extension .xlsm nor .xlsx is working

    this code:

    If sFileSaveName False Then
    ActiveWorkbook.SaveAs sFileSaveName
    End If

    is saving a copy of the file but closes the original document to reopen the saved copy.

    please help

  10. PNRao
    April 1, 2015 at 7:06 PM — Reply

    Hi,

    SaveAs will save the file with the changes in the specified location. It will not neither close the old file nor open new file.
    when you open the file, it will always stores in the temporary memory, when you Save the file, this will just save the changes to the existing file – SaveAs will save the file in the specified location.

    Hope this clarifies your query.
    Thanks-PNRao!

  11. Saputro
    July 18, 2015 at 6:19 PM — Reply

    Hi
    How to keep text format when save as to *.csv or at least to show “keep using that format” question dialog with VBA

    Thanks

  12. :)
    November 27, 2015 at 4:56 PM — Reply

    save file as .xls…. for that first go to the “save as type”.. then choose “.xls” extension file… ur file automatically will b saved as “filename.xls”…

  13. DLoughry
    December 17, 2015 at 8:01 PM — Reply

    What code do I use so that the file saves to a folder in a users My Documents. Now, the folder might not exist the first time they are saving the file, so I would need to incorporate that as well into the code.

    Example path: C:UsersDocumentsWorkbook1.xlsx

    Thanks in advance!

  14. DLoughry
    December 17, 2015 at 8:02 PM — Reply

    What code do I use so that the file saves to a folder in a users My Documents. Now, the folder might not exist the first time they are saving the file, so I would need to incorporate that as well into the code.

    Example path: C:UsersDocumentsWorkbook1.xlsx

    Thanks in advance

  15. DLoughry
    December 17, 2015 at 8:05 PM — Reply

    The example path did not show correctly in my initial comment. Between Users and Documents it should show ” and between Documents and the file name it should show “.

    C:Users”Documents”Workbook1.xlsx

  16. DLoughry
    December 17, 2015 at 8:07 PM — Reply

    Argh…Ok. Where the quotes are should be username and New Folder respectively.

    Sorry for all the extra comments.

  17. Guz
    January 2, 2016 at 2:39 AM — Reply

    Great, it really helped me!!

  18. T.Lajos
    April 12, 2016 at 11:09 PM — Reply

    Hi,
    I tried several code to save my excxel file. All attemts including your “Save Workbook in the same location of the Macro (this) Workbook” results the same: I get a new but empty file (with your code workbookname.xls) in the same directory where workbook using ThisWorkbook.There is data in cells of original workbook but the saved one is empty…(excel 2007)..
    Could you Have please some idea what couses this curious phenomena?

  19. MK
    July 27, 2016 at 4:26 PM — Reply

    I have the same problem. Maybe sone ideas?

  20. Patrick Mahoney
    August 26, 2016 at 2:41 AM — Reply

    Hi to all,
    I am using Excel 2011 for Mac. In a macro file (.xlsm) triggered from my database, with an AutoOpen macro, I import data from my database, format the spreadsheet and then save it as a .xlsx file. My problem is that when the macro does a SaveAs, there is a dialog box telling me that the macros will be removed in the .xlsx file and then required that I click on the save button. How can I bypass that dialog and finish the save process without user intervention?

    My code:

    ThisFile = Range(“B2”).Value
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:=ThisFile, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=True
    Range(“A1”).Select
    Application.DisplayAlerts = True
    Application.Quit

  21. Sub
    December 29, 2016 at 7:20 PM — Reply

    I am passing a password through the variable “f” and trying to protect the workbook but it is not working.
    Can you tell me how?
    ActiveWorkbook.Protect Password:=f, Structure:=True, Windows:=False

  22. Shane
    June 16, 2017 at 8:21 PM — Reply

    Hi All,

    I am trying to add in code to save the below to a shared drive with a date in the name of the file ie “abc 16.06.2017” Would also love to send a print screen in the body of the mail too – can anyone help with that?

    Thanks a mill

    Sub Mail_ControlSheet()

    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim Sourcewb As Workbook
    Dim Destwb As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
    .ScreenUpdating = False
    .EnableEvents = False
    End With

    Set Sourcewb = ActiveWorkbook

    ActiveSheet.Copy
    Set Destwb = ActiveWorkbook

    With Destwb
    Select Case Sourcewb.FileFormat
    Case 51: FileExtStr = “.xlsx”: FileFormatNum = 51

    End Select

    End With

    Set OutApp = CreateObject(“Outlook.Application”)
    Set OutMail = OutApp.CreateItem(0)

    With Destwb
    With OutMail
    .to = “xx@abc.com”
    .CC = ”
    .BCC = ”
    .Subject = “XX ” & Format(Date, “dd-mm-yyyy”)
    .Body = “Hi All,” & vbCrLf & vbCrLf & “XX.” & vbCrLf & vbCrLf & “Many Thanks” & vbCrLf & “Shane”
    .Attachments.Add “hbeu.adroot.hsbcgb001Redir GB USERS LAPTOP43960692DocumentsShanehello.xlsm.”
    .Display
    End With
    On Error GoTo 0
    .Close savechanges:=False
    End With

    End Sub

  23. George
    September 9, 2017 at 1:52 AM — Reply

    I am trying to save file RENT.xls in different folders:
    My Documents/Jan 17/ RENT.xls
    My Documents/Feb/RENT.XLS
    My Documents/Mar/RENT.xls
    etc
    etc

    Can someone help please?

  24. PNRao
    September 12, 2017 at 11:27 PM — Reply

    Here is the Macro to save the file into required folders using VBA.

    Sub sbSaveFileInToDifferentFolders()
    
    Set wb = Workbooks.Open("C:TempRENT.xls")
    
    MyFoldersArray = Array( _
    "C:TempFolderA", _
    "C:TempFolderB", _
    "C:TempFolderC" _
    )
    
    For iCntr = 0 To UBound(MyFoldersArray, 1)
        wb.SaveAs MyFoldersArray(iCntr) & " & wb.Name
    Next
    
    End Sub
    

    Thanks!

  25. hi,
    After saving the workbook in a specific folder as shown below
    Sub ExampleToSaveWorkbook()

    Workbooks. Add
    ‘Saving the Workbook
    ActiveWorkbook.SaveAs “G:LookupExercise.xlsx”
    ‘OR
    ‘ActiveWorkbook.SaveAs Filename:=”G:LookupExercise.xlsx”

    End Sub
    I am not able to see the content in the workbook why?. I am a little bit confused in the context can you explain please.
    Thanks

  26. Aaron
    February 14, 2019 at 11:48 PM — Reply

    I need help with the following. I need to save a copy of a workbook with the File Name and the Date (A Save at that moment), and then open that saved Copy. Currently the below code will Save the file and rename the document correctly (except it will do .xlsm.xslm and I cant fix this…) but when you open the document, there is no information. Its completely blank…. so its not a save as, its just opening a new file and naming based on my file.

    Can someone help me correct this code so that it saves all of my data, renames the file and opens it up once saved?

    Sub snwb()
    Dim thisWb As Workbook, d As Integer

    Set thisWb = ActiveWorkbook
    Workbooks.Add
    d = InStrRev(thisWb.FullName, “.”)
    ActiveWorkbook.SaveAs filename:=Left(thisWb.FullName, d – 1) & Format(Now, ” yyyy.mm.dd”) & Mid(thisWb.FullName, d) & “.xlsm”, FileFormat:=52

    ActiveWorkbook.Close savechanges:=False
    End Sub

  27. Aaron
    February 15, 2019 at 4:36 AM — Reply

    I have an updated code that seems to be working correct, however, I need this to work with Office 365. I need the file to save back to the same location on 365. Any ideas?

    Sub SaveToRelativePath()
    Dim relativePath As String
    relativePath = ThisWorkbook.path & ” & ActiveWorkbook.Name
    ActiveWorkbook.SaveAs filename:=ThisWorkbook.Name & ” FINAL BID” & “.xlsm”, FileFormat:=xlOpenXMLWorkbookMacroEnabled
    End Sub

  28. Sivaprakasam
    October 28, 2019 at 12:57 PM — Reply

    Hi can u provide the below u r VBA including view list (file size, created date and modified date), due to i have confusing the new file or old file.

    Save a Workbook to a Specific Folder

    Sub ExampleToSaveWorkbook()

    Workbooks.Add
    ‘Saving the Workbook
    ActiveWorkbook.SaveAs “C:WorkbookName.xls”
    ‘OR
    ‘ActiveWorkbook.SaveAs Filename:=”C:WorkbookName1.xls”

    End Sub

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

I have created a sheet in vba Excel. I would like to save it the current directory, but not in absolute path, then, when this is executed somewhere else, there won’t be problem.

Can somebody help ?

0m3r's user avatar

0m3r

12.2k15 gold badges33 silver badges70 bronze badges

asked Dec 21, 2010 at 9:02

Ndiol Dia's user avatar

I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path to get a relative file path:

Sub SaveToRelativePath()
    Dim relativePath As String
    relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
    ActiveWorkbook.SaveAs Filename:=relativePath
End Sub

Andrew Richesson's user avatar

answered Dec 21, 2010 at 11:53

Alex P's user avatar

Alex PAlex P

12.2k5 gold badges51 silver badges69 bronze badges

1

VBA has a CurDir keyword that will return the «current directory» as stored in Excel. I’m not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.

MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"

This assumes that the sheet you want to save has never been saved and you want to define the file name in code.

answered Dec 21, 2010 at 15:24

Dick Kusleika's user avatar

Dick KusleikaDick Kusleika

32.5k4 gold badges51 silver badges73 bronze badges

2

If the Path is omitted the file will be saved automaticaly in the current directory.
Try something like this:

ActiveWorkbook.SaveAs "Filename.xslx"

0m3r's user avatar

0m3r

12.2k15 gold badges33 silver badges70 bronze badges

answered Jun 10, 2015 at 14:26

Jonas Arnout's user avatar

0

Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:propertycaliforniasacramentoworkbook.xlsx, use this to move the property to berkley:

workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "" & "newFileName.xlsx"

Only works if your file structure contains one instance of the text used to replace. YMMV.

answered Jul 18, 2014 at 15:36

Tim Schimandle's user avatar

0

Сохранение файла рабочей книги 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 и т.д. в папке «Документы».


Like this post? Please share to your friends:
  • Vba excel сохранить файл word
  • Vba excel сохранить только один лист
  • Vba excel сохранить один лист в файл
  • Vba excel сохранить лист в word
  • Vba excel сохранить копию книги