I have an excel file, where we have created a custom sub that, when saving, presents the user with a Save As dialog that limits the list of available file types a user can save as. This has been used by a company for several years as a template - so they have hundreds of excel files saved in various locations with the following macro in it:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
' If user is doing a 'Save As', set the file type as "Excel Macro-Enabled Workbook",
' and set the list of available extensions they can save as.
Dim xFileName As String
Dim xFileExt As String
If SaveAsUI <> False Then
Cancel = True
xFileName = Application.GetSaveAsFilename("<job name goes here> CHANNEL SCHEDULE", "CSV UTF-8 (Comma delimited) (*.csv), *.csv," _
& "Excel Macro-Enabled Template (*.xltm), *.xltm," _
& "Excel Macro-Enabled Workbook (*.xlsm), *.xlsm," _
& "Excel Workbook (MACROS DISABLED) (*.xlsx), *.xlsx," _
& "", 3, "Save As xlsm file")
If xFileName <> "False" Then
Application.EnableEvents = False
' Get the file extension.
xFileExt = Right(xFileName, Len(xFileName) - InStrRev(xFileName, "."))
' Save the file.
Select Case xFileExt
Case "csv"
ActiveWorkbook.SaveAs Filename:=xFileName, FileFormat:=xlCSV
Case "xltm"
ActiveWorkbook.SaveAs Filename:=xFileName, FileFormat:=xlOpenXMLTemplateMacroEnabled
Case "xlsm"
ActiveWorkbook.SaveAs Filename:=xFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Case "xlsx"
ActiveWorkbook.SaveAs Filename:=xFileName, FileFormat:=xlOpenXMLWorkbook
Case Else
MsgBox "Error saving as the selected file type. Please try again, or try a different file type. Sorry."
End Select
Application.EnableEvents = True
Else
'MsgBox "Save As Operation Cancelled."
Cancel = True
Exit Sub
End If
End If
End Sub
That same file also happens to have "Always create backup" setting enabled as shown in the photo below, so that when any of these files are opened excel automatically creates a file in the same dir as the file just opened called "Backup of < file name you just opened >".
The problem is that now they need to disable this feature on all their excel documents, or at least give an end-user the ability to disable it themselves so they can do it manually.
The only way I have found to disable this feature is by going to Save As > Tools > General Options:
However, when using the Application.GetSaveAsFilename method, the "General Options" option from the Tools dropdown is no longer available as shown below:
My questions:
Is there another from the excel GUI to disable the "Always create backup" setting if they cannot get to it from their current Save As dialogs?
Or is there another way to 'enable' the General Options dialog from the custom Save As dialog creaed by the Application.GetSaveAsFilename method?
Is there a way to programmatically change (disable) this backup setting?
Thanks to VBasic2008 and Skin in the comments above.
Adding the CreateBackup:=False flag to the save/save as process will disable the "Always create backup" setting.
So:
ActiveWorkbook.SaveAs Filename:=xFileName, FileFormat:=xlCSV
Changes to:
ActiveWorkbook.SaveAs Filename:=xFileName, FileFormat:=xlCSV, CreateBackup:=False
Related
How do I save or export an Excel sheet to a csv file?
Sheet 1 is where the convert button located.
Sheet 2 contains the records I want save or export.
I want to select location and file name for that file. Something like this
Sub FileSaveExcel()
Dim s As Worksheet
For Each s In Sheets
If s.Name = "Template" Then
Dim wb As Workbook, InitFileName As String, fileSaveName As String
InitFileName = ThisWorkbook.Path & "\Template" & Format(Date, "yyyymmdd")
Sheets("Template").Copy
Set wb = ActiveWorkbook
fileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitFileName, _
filefilter:="Excel files , *.csv")
With wb
If fileSaveName <> "False" Then
.SaveAs fileSaveName
.Close
Else
.Close False
Exit Sub
End If
End With
End If
Next s
End Sub
The file was was successfully exported.
Upon opening it, it prompted me this message:
The file and extension of "filename.csv" don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you it anyway?
I choose yes. I notice the formats are set in .xlsm but the file extension was already in .csv.
I have the following VBA:
Sub Create_Sent_File()
ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\" & "Sent_File" & ".xlsm"
ActiveWorkbook.Close SaveChanges:=False
End Sub
The code creates a new file called "Sent_File" on the desktop of the user.
All this works fine so far.
However, after the file is created I want to close the original Excel file.
The exact same way I would do it if I have three Excel files open and then I close one of them.
Therefore, I tried to go with this formula:
ActiveWorkbook.Close SaveChanges:=False
Now, the issue is that the workbook is closed but Excel somehow remains open:
What do I need to change in my code so:
a) The current workbook in which I run the VBA is closed.
b) Other workbooks in Excel remain open.
c) Excel does not stay open as seen in the screenshot.
You're almost there, but you need a reference to the parent application before you then trigger its closure.
Sub Create_Sent_File()
Dim xlParent As Excel.Application
ActiveWorkbook.SaveCopyAs "C:\Users\" & Environ("Username") & "\Desktop\" & "Sent_File" & ".xlsm"
ActiveWorkbook.Saved = False
Set xlParent = ActiveWorkbook.Parent
xlParent.Quit
End Sub
Having set the Saved flag for the current workbook to False you can close the host Excel app without triggering any confirmation boxes.
If you have other workbooks open that you also want to close without confirmation, you'll need to work through the Workbooks collection, setting the Saved property of each to False before then proceeding with quitting the host Excel app.
I am writing a piece of code in Excel VBA in which I needed to create a macro which allows the user to click the ActiveX button as a result of which the file is then saved to a specified location. Once this new file is created, I wanted to code so the new file (which successfully saves in the alternate specified location) does not have the ActiveX Command Button is not present. Also, once the button is clicked from the original file, I wanted to somehow make the master file close and the newly saved file to automatically open. Please can someone help?
Code so far:
Sub CommandButton1_Click()
ActiveSheet.Copy
Dim SaveName As String
SaveName = ActiveSheet.Range("C1").Text
With ActiveWorkbook
.SaveAs "File path Specified" & _
SaveName & ".xls"
.Close 0
End With
End Sub
My first solution (depending on what you really need to do) is the following:
Firstly you will need this:
Me.SaveCopyAs "<full_Path>"
See more on this here: https://msdn.microsoft.com/en-us/library/office/ff835014.aspx
This will create a copy of the file to the specified path with whatever name you want. Before you do that, you could hide your button and then use save as copy to save it with the button hidden.
Finally if you want to close the original and open the copy then you have to give to the copy a different name. Then open the new file and close the original.
Your code should look similar to this:
Sub CommandButton1_Click()
ActiveSheet.Copy
Dim SaveName As String
SaveName = ActiveSheet.Range("C1").Text
With ActiveWorkbook
.Worksheets("<your_worksheet>").CommandButton1.visible = False
.SaveCopyAs "File path Specified" & SaveName & ".xls"
End With
Workbooks.Open ("File path Specified" & SaveName & ".xls")
Workbooks("<Original_name.xlsm>").close False
End Sub
Another Solution could be saving the workbook with SaveAs. Before that save the orginal. Hide the button. And saveas will close the original and open the new one automatically.
Your code should look something like that:
Sub CommandButton1_Click()
ActiveSheet.Copy
Dim SaveName As String
SaveName = ActiveSheet.Range("C1").Text
With ActiveWorkbook
.Save
.Worksheets("<your_worksheet>").CommandButton1.visible = False
.SaveAs "File path Specified" & SaveName & ".xls"
End With
End Sub
I would like to have a button on this excel sheet whose name should be “Save as PDF”.
When I press this button it should save the excel sheet’s all data into PDF at the path- M:\formats\ ‘File Name’
‘File Name’ should be the value of cell No H8.
In another words when I click “Save as PDF” button it should save the excel file in pdf form, into the above mentioned path and also with the name whichever is written in cell no H8.
For example, if the name ANDREW PITTERSON is written in H8 cell then it should save with the same name I.e. ANDREW PITTERSON.
Kindly look at this snapshot.
http://i.imgur.com/JJdlFSi.jpg
THANKS
Here's a link to a great simple article, to do this sort of thing. http://www.contextures.com/excelvbapdf.html
I've tested the code example in Excel 2013 and it works fine. The code asks the user what directory to save the PDF in.
But your question says that you also want to save to a specific location (without user intervention) and to get the filename from a cell.
Update - And you'd also like to save the file as an XLSM, once the PDF is created.
The code below does what you're after (all credit to the original author, but my own OCD led me change var names to a format that I like).
I'm guessing the OP would like to know HOW it was done, rather than just have the answer, so I've tried to make the example easy to follow, rather than trying to observe best practice - I'd appreciate not being down-voted for this.
Please note, you must first open the Excel Code window, got to Tools, then References and select 'Microsoft Scripting Runtime' then click Ok. This lets you use many useful functions.
I keep the directory path (hard coded) and the filename separate, so that I can get the 'BaseName' in a clearer way. Obviously this could be done in less lines, but at the risk of making it harder to follow.
Sub ExportAPDF_and_SaveAsXLSM()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
strBasePath = "M:\formats\"
strFileName = Range("H8")
On Error GoTo errHandler
Set wsThisWorkSheet = ActiveSheet
wsThisWorkSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strBasePath & strFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
' Now we need to get rid of the .PDF extension. Many ways to code round this, but here is a built in function.
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsm"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
MsgBox "Workbook now saved in XLSM format."
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Just add the button (ActiveX Button) to your worksheet and call this sub from the buttons code window (or just paste the code directly into the Button code window).
Hope that helps.
ADDED:
To save the file as an XLSX (No Macros), then replace the code toward the end of the SUB with:
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName, FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = False
I have a template that user will open up, select the text file and VBA does all the magic. At the end of the code I have the SaveAs dialog box come up, user type in name and saves to appropriate location. I have this code sitting in a module of the main temmplate. The problem I have is the formatted file has the module in it where the code sits. I don't want that. I know I've figured this out before but today is not that day. Relevant code pasted below. I've tried changing the file formats, moving code to a worksheet. What am I missing/forgetting?
Filename = "WhateverName_"
SaveThiisFile = Application.GetSaveAsFilename(InitialFileName:=Filename, _
fileFilter:="Excel Files (*.xls), *.xls", _
FilterIndex:=1, Title:="Save As")
If ThisFile = False Then Exit Sub
ActiveWorkbook.SaveAs Filename:=SaveThisFile
ActiveWorkbook.Close (False)