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)
Related
So i have this VBA at work, that I made a while ago. It used to work perfectly, but as of today it will not save my file after it opens the Save as window. It just goes to the MsgBox ive given it.
At first the problem was that LDate = Date somehow started returning the date with a forward slash. Ive fixed this by adding a format for LDate. But the bigger problem remains. No matter what i do, what code i remove or add, what name i write manually, the file wont save in any folder i give it.
Sub Export()
'
' Export Macro
'
' copy range from work workbook, create a new workbook and paste selection
Sheets("NewTemplate").Range("A1:M29").Copy
Workbooks.Add
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveSheet.Paste
' rename active sheet and active workbook
ActiveSheet.Name = "Create"
ActiveWorkbook.Windows(1).Caption = "Newly Generated Table"
Range("A1").Select
Application.CutCopyMode = False
' open Save As window, set file save name to custom prefix + date
Dim IntialName As String
Dim fileSaveName As Variant
InitialName = "Import_Feature_Values_"
Dim LDate As String
LDate = Date
LDate = Format(Now, "dd_mm_yyyy")
fileSaveName = Application.GetSaveAsFilename(FileFilter:= _
"Microsoft Excel Macro- Enabled Worksheet (*.xlsm), *.xlsm", InitialFileName:=InitialName & LDate)
'error box if filesavename fails
If fileSaveName <> False Then
MsgBox "Failed to Save as " & fileSaveName
End If
'
End Sub
GetSaveAsFilename does not save a file.
It only does what the function name says: Get a SaveAs filename from the dialog box.
So your variable fileSaveName just contains a file path and file name that was chosen in the dialog box, and you still need to save the file yourself.
Fore example to save the current workbook (that workbook code is running at) with the chosen filename:
ThisWorkbook.SaveAs Filename:=fileSaveName
or for the active workbook (that workbook that is on top):
ActiveWorkbook.SaveAs Filename:=fileSaveName
For macro enabled files define a file format according to XlFileFormat-Enumeration:
ActiveWorkbook.SaveAs Filename:=fileSaveName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
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
I have a macro that saves the current workbook as CSV MSDOS format.
Here's my code:
Sub Save_CSV()
Dim Location, FileName As String
Location = "C:\Users\myawesomename\OneDrive\Desktop\GM MRP\"
FileName = Left(ActiveWorkbook.name, Len(ActiveWorkbook.name) - 5)
ActiveWorkbook.SaveAs FileName:= _
Location & FileName & ".csv", FileFormat:= _
xlCSVMSDOS, CreateBackup:=False
ActiveWorkbook.Save
End Sub
After I use this macro, I'm no longer working on the xlsv. Rather, I'm working on the CSV version with all the sheets still present. If I close the workbook without saving it, I can then open the CSV file and only the first sheet is present. It's fine that only the first sheet is present but I want it to save a separate CSV file (with the first sheet only present) while continuing to work on the XLSX file without opening the CSV at all. I'm not trying to save each sheet as a separate file.
I tried several things including changing "Activeworkbook.SaveAs" to "Activeworkbook.savecopyas" but I couldn't achieve the desired result.
Thank you,
I have a hard time identifying this issue. I have a macro that selects multiple sheets within a workbook and saves it as a PDF. The file is placed correctly into the folder and sometimes it even opens correctly. However, most of the time the PDF is corrupted and gives me the following error.
I cannot replicate instances when it works. The sheet "MSPG Chart" is a chart sheet, i.e. I moved a chart to its own sheet called "MSPG Chart". If I manually save the file it works.
Below is the code I use:
NewPathAssembly is my save path, which works as intended.
Sub Create_PDF_StandAlone()
Dim NewPathAssembly as String, Name as String
Dim PDFName as Variant
On Error GoTo ErrLine
NewPathAssembly = "C:\"
Name = "B2110 - xx_30 - MS Peergroup"
PDFName = InputBox("Enter PDF name here.", "PDF title", Name)
Sheets(Array("Overview", "MSPG Chart")).Select
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False, PrToFilename:= _
NewPathAssembly & PDFName & ".pdf"
Sheets(1).Select
Exit Sub
ErrLine: MsgBox "Please close the current PDF file"
End Sub
Adding the argument ActivePrinter:="Microsoft Print To PDF"
worked. It appears that since it defaulted to another printer it somehow corrupted the file.
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