Saving Workbook Copy using VBA won´t include Doc Properties - excel

I´m using a VBA program that, after filling all the Textboxes in a vba userform, saves the workbook as PDF and also a copy of that workbook (xlsm). Part of the program is that the values of certain Textboxes are added as Doc Properties. It works that those properties are added to the original workbook and to the PDF, but not to the copy of the workbook and I don´t know why. Below is the code responsible for adding Doc Properties and saving the documents.
I have already tried to add "IncludeDocProperties:=True" to the part where the copy is saved, but that does not work.
ActiveWorkbook.BuiltinDocumentProperties("Keywords") = Userform1.TextBox1.Value & " " & UserForm1.TextBox2.Value
Dim varResult As Variant
Dim ActBook As Workbook
varResult = Application.GetSaveAsFilename(FileFilter:= _
"XLSM (*.xlsm), *.xlsm", Title:="save file", _
InitialFileName:=Userform1.TextBox1.Value)
Worksheets("Example").Copy
With ActiveWorkbook
.SaveAs Filename:=varResult, FileFormat:=xlOpenXMLWorkbookMacroEnabled
.Close savechanges:=True
End With
'PDF EXPORT
ActiveSheet.ExportAsFixedFormat Filename:=varResult, Type:=xlTypePDF, OpenAfterPublish:=True, _
IncludeDocProperties:=True

Related

Convert .xlsm to .csv [duplicate]

I appreciate there are lots of entries like save individual excel sheets as csv
and Export each sheet to a separate csv file - But I want to save a single worksheet in a workbook.
My code in my xlsm file has a params and data sheet. I create a worksheet copy of the data with pasted values and then want to save it as csv. Currently my whole workbook changes name and becomes a csv.
How do I "save as csv" a single sheet in an Excel workbook?
Is there a Worksheet.SaveAs or do I have to move my data sheet to another workbook and save it that way?
CODE SAMPLE
' [Sample so some DIMs and parameters passed in left out]
Dim s1 as Worksheet
Dim s2 as Worksheet
Set s1 = ThisWorkbook.Sheets(strSourceSheet)
' copy across
s1.Range(s1.Cells(1, 1), s1.Cells(lastrow, lastcol)).Copy
' Create new empty worksheet for holding values
Set s2 = Worksheets.Add
s2.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
' save sheet
s2.Activate
strFullname = strPath & strFilename
' >>> BIT THAT NEEDS FIXIN'
s2.SaveAs Filename:=strFullname, _
FileFormat:=xlCSV, CreateBackup:=True
' Can I do Worksheets.SaveAs?
Using Windows 10 and Office 365
This code works fine for me.
Sub test()
Application.DisplayAlerts = False
ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=strFullname, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
It's making a copy of the entire strSourceSheet sheet, which opens a new workbook, which we can then save as a .csv file, then it closes the newly saved .csv file, not messing up file name on your original file.
This is fairly generic
Sub WriteCSVs()
Dim mySheet As Worksheet
Dim myPath As String
'Application.DisplayAlerts = False
For Each mySheet In ActiveWorkbook.Worksheets
myPath = "\\myserver\myfolder\"
ActiveWorkbook.Sheets(mySheet.Index).Copy
ActiveWorkbook.SaveAs Filename:=myPath & mySheet.Name, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Next mySheet
'Application.DisplayAlerts = True
End Sub
You just need to save the workbook as a CSV file.
Excel will pop up a dialog warning that you are saving to a single sheet, but you can suppress the warning with Application.DisplayAlerts = False.
Don't forget to put it back to true though.
Coming to this question several years later, I have found a method that works much better for myself. This is because the worksheet(s) I'm trying to save are large and full of calculations, and they take an inconvenient amount of time to copy to a new sheet.
In order to speed up the process, it saves the current worksheet and then simply reopens it, closing the unwanted .csv window:
Sub SaveThisSheetInParticular()
Dim path As String
path = ThisWorkbook.FullName
Application.DisplayAlerts = False
Worksheets("<Sheet Name>").SaveAs Filename:=ThisWorkbook.path & "\<File Name>", FileFormat:=xlCSV
Application.Workbooks.Open (path)
Application.DisplayAlerts = True
Workbooks("<File Name>.csv").Close
End Sub
Here the Sheet and csv filename are hardcoded, since nobody but the macro creator (me) should be messing with them. However, it could just as easily be changed to store and use the Active Sheet name in order to export the current sheet whenever the macro is called.
Note that you can do this with multiple sheets, you simply have to use the last filename in the close statement:
Worksheets("<Sheet 1>").SaveAs Filename:=ThisWorkbook.path & "\<File 1>", FileFormat:=xlCSV
Worksheets("<Sheet 2>").SaveAs Filename:=ThisWorkbook.path & "\<File 2>", FileFormat:=xlCSV
[...]
Workbooks("<File 2>.csv").Close

I am unable to get VBA in Excel to save a file. The Save As dialog box opens with the file name as scripted but it never saves [duplicate]

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

VBA 1004 error on selecting "No" or "Cancel" when asked to replace file during SaveAs

I have VBA where the user fills out a template, then saves as .XLSM and PDF.
The .XLSM saves as the entire workbook, but the PDF is only 2 worksheets. Both files are named after a variable cell in the workbook and a file location is suggested, but can be changed by the user.
Everything works until the user is warned that they are overwriting an existing file. If they select "no" or "cancel," then they get an error. Ideally, I would like for the sub to just exit and neither the PDF or .XLSM is saved. I have tried On Error, but cannot get the whole thing to work. Other solutions seem to take away some functionality (variable file name, different sheets printing/saving, initial file location, etc.).
Below is my code if anyone can help:
Sub SaveToPDF2()
Dim strFilename As String
Dim rngRange As Range
Dim fileSave As FileDialog
Set fileSave = Application.FileDialog(msoFileDialogSaveAs)
'Considering Sheet1 to be where you need to pick file name
Set rngRange = Worksheets("template").Range("b3")
'Create File name with dateStamp
strFilename = rngRange.Value & ".process." & Format(Date, "mm.dd.yyyy")
With fileSave
' Your default save location here
.InitialFileName = "U:\221 Released Drawings\" & strFilename
If .Show = -1 Then
ActiveWorkbook.SaveAs filename:=strFilename & ".xlsm", FileFormat:=52
ThisWorkbook.Sheets(Array("process", "signoff")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=strFilename _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
Else: Exit Sub
End If
End With
End Sub
Try inserting the next code line, just before With fileSave:
If Dir(strFilename & ".xlsm") <> "" then Exit Sub
If such a file already exists, the code is exited on the above inserted line...

Exporting an Excel sheet to a .csv file having options to select path and filename using VBA

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.

Turning PDF Macro into Excel

I am trying to convert this code that instead of saving PDF copies it saves the individual sheets as Excel workbooks instead. I have tried changing the Export as fixed format to xlsm but it appears to have a run time error. Very new to this but any help would be appreciated.
Sub PDF()
Dim xWs As Worksheet
Application.ScreenUpdating = False
For Each xWs In ThisWorkbook.Worksheets
If xWs.Visible = True Then
If xWs.Name <> "HOME" And xWs.Name <> "DATA" Then
xWs.Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\PDF P&L\" & Range("G1").Value & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
End If
Next xWs
Application.ScreenUpdating = False
End Sub
The .ExportAsFixedFormat method doesn't support export to excel file formats as per the documentation
The action you're most likely looking for is .move. When not specified with where to move, this will create a new workbook with the moved sheet. You can then use workbooks(Workbooks.count) to access the latest created workbook. See example code below:
Dim wb As Workbook
ActiveSheet.Move
Set wb = Workbooks(Workbooks.Count)
wb.SaveAs Filename:="yournamehere", FileFormat:=xlOpenXMLWorkbookMacroEnabled 'etc...
Please note, when this is done to the last remaining or only sheet in the workbook, this will throw an error. For more info on the .move method, see the link. For file formats to use see here.
Also, when moving a sheet, all the VBA code on the worksheet will be pulled across, but the modules related to the workbook won't. So attempting to save it as anything but xlsm when it has any code on it will result in a prompt or error.

Resources