I have added a button in excel sheet and added following codes in vba window of that button. Now when I click this button i.e. when I run the codes it saves the excel sheet in pdf form whose name it takes from cell no H8 and saves it at M:\formats. Moreover it also saves the same excel sheet in .xlsx format at M:\formats\excels. But here the problem is when I run the codes it closes the excel sheet in which I have added the codes and opens the file which is saved by the codes. For example I made abc.xlsm excel sheet and added the codes in vb window, now xyz is written in cell no h8 in abc.xlsm excel sheet, now when I will run the codes it closes abc.xlsm and all codes are shown in xyz.xlsx excel sheet. I want it should only save the file in xlsx format it requisite location. It should not close the base file (which is abc.xlsx in the above example) and should not open the saved file (which is xyz.xlsx in the above example). Moreover I want that the saved file (xyz.xlsx in the above example) should not contain any vba coding. In another words it should be just like the backup copy for the base file (which is abc.xlsx in the above example). Kindly help me in to modify these codes to them as I want. I will be highly obliged to you. Thanks
Sub ExportAPDF_and_SaveAsXLSX()
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."
strBasePath = "M:\formats\excels\"
strFileName = Range("H8")
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName,
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = False
MsgBox "Workbook now saved in XLSX format."
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Here is the code, with just two small changes. Both new sets of lines have the comment "New" in front of them.
Also just tidied up the error handling routine a little bit.
The way it works is this:
Store the filename of the current workbook in the variable 'strMasterWorkbookFilename'
The PDF file is created by 'exporting' the worksheet.
The Excel worksheet is then saved as an XLSX. This effectively 'closes' the original workbook.
3.1 The Button ("Button 8") is removed from the new XLSX worksheet and the workbook is saved again.
The code then re-opens the original workbook ('strMasterWorkbookFilename') and closes the current workbook.
Notes - Saving as the XLSX will remove the Macro code from the saved file. The Macro will remain in the main 'master' file.
Sub ExportAPDF_and_SaveAsXLSX()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
' NEW
Dim strMasterWorkbookFilename As String
strMasterWorkbookFilename = ThisWorkbook.FullName
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."
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName, FileFormat:=xlOpenXMLWorkbook
wsThisWorkSheet.Shapes("Button 8").Delete
ActiveWorkbook.Save
Application.DisplayAlerts = False
MsgBox "Workbook now saved in XLSX format."
' NEW
Workbooks.Open strMasterWorkbookFilename
Workbooks(strFileName).Close SaveChanges:=False
exitHandler:
Exit Sub
errHandler:
MsgBox "Error Saving file. The error is " & vbCrLf & Chr(34) & Err.Description & Chr(34)
Resume exitHandler
End Sub
Thanks for posting this as a new question. If I'd carried on modifying the original code in the first question, it would not have been useful for anyone else reading your original post.
Related
ive been working on some code for a while but cannot seem to get it to work.. think im nowhere near if im honest..
I want to program a button into an excel doc to go to a folder i.e. D:\Work\
which has lots of excel spreadsheets in, and save everyone one as a separate PDF doc?
thanks in advance
The code below Loop through all files and then save all worksheets with in a workbook as PDF. I have commented the code to help you understand it.
Option Explicit
Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String
Dim wbktoExport As Workbook
Dim strSourceExcelLocation As String
strSourceExcelLocation = "D:\Work\XLS\"
'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.xls*")
Do While Len(strWorkbook) > 0
'Open the workbook
wbktoExport = Workbooks.Open(strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport)
'Get next workbook
strWorkbook = Dir
'Close Excel workbook without making changes
wbktoExport.Close False
Loop
End Sub
Sub Export_Excel_as_PDF(ByRef wbk As Workbook)
Dim strTargetPDFLocation As String
strTargetPDFLocation = "D:\Work\PDF\"
'Select all worksheets in the opened workbook
wbk.Sheets.Select
'Activate first worksheet
wbk.Sheets(1).Activate
'Export as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
strTargetPDFLocation & wbk.Name & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
End Sub
I am writing a macro that automates a daily report that I send out each day. One of my last items is to write a script that saves the formatted excel sheet as a PDF (through a print to pdf option), and save it in a specific folder. I have the following written, however, it still prompts the user as to where to save it.
What would be a better way, or a way in general, to have it save automatically to a folder somewhere on my desktop?
Sub printToPDF()
Worksheets("general_report").PageSetup.CenterVertically = False
ActiveWindow.SelectedSheets.PrintOut Copies:=1, ActivePrinter:="Foxit Reader PDF Printer"
End Sub
This should do the work,
Sub printToPDF()
Dim FilePath As String
Dim FileName As String
FilePath = "C:\Users\userName\Desktop\" 'Change as per your username
ActiveSheet.Copy 'Copy a worksheet to a new workbook
'It saves .PDF file at your Descrop with the name of the worksheet
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FilePath & ActiveSheet.Name, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'Closing a newly created workbook without saving it
Application.DisplayAlerts = False
ActiveWorkbook.Close
End Sub
Hello thanks for reading my question, I have a Workbook with hidden templates and most of them are used as Excel .xlsx spreadsheet however one of them requires a module to be inserted for it to work. I thought simple enough just add a param to my function that creates the workbook.
It doesn't seem to work because i get an error "Error Number 1004 This extension can not be used with the selected file type. Change the file extension in the file name text box or select a different file type blabla"
Public Function gWrkBook(template As String, Optional wbMacro As Boolean) As Workbook
Dim wbNew As Workbook
Dim wsTemplate As Worksheet, wsSummary As Worksheet
Set wsTemplate = ThisWorkbook.Worksheets(template) '===== Create new workbook and copy template
wsTemplate.Visible = True
'
Set wbNew = Workbooks.Add 'Create New file
wsTemplate.Copy Before:=wbNew.Sheets(1) 'Copy template to new workbook
'Rename sheet
On Error GoTo ErrSheetName
wbNew.Sheets(1).Name = "SUMMARY"
Set wsSummary = wbNew.Sheets("SUMMARY")
wsTemplate.Visible = False '===== Clean up
Call gRemoveUnwanted("sheets", wbNew) 'Mod7 '==== Get SaveAs filename and save file
If wbMacro = True Then
vFileName = Application.GetSaveAsFilename(Filname, "Excel Macro-Enabled workbook(*.xlsm), *.xlsm", Title:="SaveAs Workbook Macro-Enabled")
Else
vFileName = Application.GetSaveAsFilename(FileFilter:="Microsoft Excel Workbooks, *.xlsx", Title:="SaveAs Workbook")
End If
On Error GoTo ErrFileName
wbNew.SaveAs Filename:=vFileName
Set gWrkBook = wbNew 'must assign it this way?? not sure why R2
Exit Function
ErrSheetName:
NewSheetName = InputBox("Worksheet exists, try a different name." & vbCrLf & "Enter Sheet Name.")
Resume
ErrFileName:
MsgBox "Error Number " & _
Err.Number & vbCrLf & _
Error(Err) & vbCrLf & _
"Try Again!", _
vbExclamation + vbOKOnly, _
"ERROR!"
vFileName = Application.GetSaveAsFilename(FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", _
Title:="SaveAs Workbook")
Resume
End Function
Try:
wbNew.SaveAs(Filename:=vFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled)
For more information, please read documentation:
VBA SaveAs
VBA File Format XlFileFormat Enumeration.
I recorded vba code to do some conditional formatting. The result is stored in the workbook itself. Now I want to force the user not to save the workbook, instead after the code is run, it should automatically save the workbook using "Save As" into a non macro file using some unique identifier such as "yyyymmmdd, hhmm.xlsx" and it should also ask the user where to save.
Additionally, it should close the workbook without saving it and open the last saved as .xlsx file. I found some codes, but they are not exactly what I am looking for. Please help.
How about this
Option Explicit
Sub SaveAs()
Dim sDate As String
Dim FileName As String
'// format Date
sDate = Format(Now, "YYYYMMDD HHMM")
'// Save As Name
FileName = sDate
'// Save path
Application.Dialogs(xlDialogSaveAs).Show FileName
End Sub
add this code below your code
Per OP Comment
This should do it - Tested on Excel 2010
Option Explicit
Sub SaveAs()
Dim xlSaveAs As String
Dim xlPath As Variant
Application.ScreenUpdating = False
'// Save As Name
xlSaveAs = "Weekly Report - " & Format(Now, "YYYYMMDD HHMM") & ".xlsx"
'// Save path
Application.DisplayAlerts = False
xlPath = Application.GetSaveAsFilename( _
InitialFileName:=xlSaveAs, _
FileFilter:="Excel Files (*.xlsx), *.xlsx", _
Title:="My Save Dialog")
If xlPath <> False Then
ThisWorkbook.SaveAs xlPath, xlOpenXMLWorkbook
Else
MsgBox "Not Valid Path" '// Cancel
End If
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Finally, You may find the Getting Started with VBA in Office 2010 article in MSDN helpful.
edit : I rewrite the code to do what you want
Public Sub SaveNewFile()
' Create a new file basing the name of the current file (without extension if it's an xlsm) and the creation time
Dim filename As String
filename = ThisWorkbook.Path & "\" & CreateObject("scripting.filesystemobject").getbasename(ThisWorkbook.Name) & Format(Now, "yyyyMMdd hhmm") & ".xlsx"
' Save the file under the new name in xlsx format
' This action close the file and reopen it with the new name
Application.DisplayAlerts = False
ThisWorkbook.SaveAs filename:=filename, FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
End Sub
I've got an Excel macro button that upon clicking, exports a number of worksheets in PDF format. VBA below.
The problem is that after the PDF has been exported the document ends up on a different worksheet to where the button is, and I cannot select any objects in the sheet or click anything in the ribbon, but I can select a cell in the sheet and I can move between sheets. (Excel 2007).
The solution I have discovered is to return to the worksheet where the button is located and click into any cell in that worksheet. Before clicking in any cell the macro button is sort of highlighted - the text is slightly darker than the other macro buttons in the page and there is a faint dotted line around the inside of the button. When I select any cell, the text returns to a normal color and the faint dotted line disappears. I am then able to select objects and use functions in the ribbon.
This is fine for me using the sheet, but as other people in my company will use this I want it to be easy to use. I would like not to have to return to the sheet where the button is to deselect the button, but be able to continue working immediately. I can share screenshots if need be
Sub PDFExportAllDashboards()
Dim myFile As Variant
Dim strFile As String
Dim ws As Worksheet
On Error GoTo errHandler
Dim arrSheets() As String
Dim sht As Worksheet
Dim i As Integer
Set ws = Worksheets("Dashboard - Focus IT")
i = 0
For Each sht In ActiveWorkbook.Worksheets
If InStr(1, sht.Name, "Dashboard") > 0 Then
ReDim Preserve arrSheets(i)
arrSheets(i) = sht.Name
i = i + 1
End If
Next sht
ThisWorkbook.Sheets(arrSheets).Select
strFile = Replace(Replace(ws.Name, " ", ""), ".", "_") _
& "_" _
& Format(Now(), "yyyy-mm-dd") _
& ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Save as")
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=myFile, _
OpenAfterPublish:=True
MsgBox "PDF file has been created."
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
At the end of your macro (right after - MsgBox "PDF file has been created.") you can complete the same steps that you did manually in VBA
Return to sheet with:
WORKBOOK_NAME.Sheets("WORKSHEET_NAME").Activate
select a cell:
Range("A1").Select
Just fill in the correct workbook and worksheet name