Macro to Save A Worksheet as Excel

shaunda101

New Member
Joined
Mar 20, 2013
Messages
6
Hello, I have code to save an excel sheet as a PDF and attach it to an email but when it try to modify it to save as an excel, it causes errors. Below is (1) the excel code I'm trying to fix; and (2) the working code for my PDF function. When I run the macro to save the excel worksheet in a new workbook, it creates the sheet in the a separate workbooks, but then gives as Run-time error '9': Subscript out of range." When I run debug, the line in red is what's highlighted. So it's not liking something with the filename/path??
(1) Code to save worksheet into new workbook (broken)
Sub SaveAsExcel2()
Dim FileFormatstr As String
Dim Fname As Variant
Dim sDate As String
Dim project As String
project = Sheets("Summary").Cells(9, 2)
Dim sheetname As String
sheetname = ActiveSheet.Cells(1, 1)
sDate = Replace(Replace(FormatDateTime(Now(), vbShortDate), "/", "."), ":", ".")
ActiveSheet.Copy
Fname = ActiveWorkbook.Path & "\" & Sheets("Summary").Cells(9, 2) & " " & ActiveSheet.Cells(1, 1) & " " & Format(sDate, "medium date") & ".xls"
ActiveWorkbook.SaveAs FileName:=Fname
ActiveWorkbook.Close
End Sub​

(2) Code to save worksheet as a PDF and Email
Sub Workbook_To_Excel_And_Create_Mail()
Dim FileName As String
'Call the function with the correct arguments
FileName = Create_PDF(ActiveWorkbook, "", True, False)
If FileName <> "" Then
'To send to specific person, put email address within quotes below; next field is subject...this part can be removed if not sending email'
Mail_PDF_Outlook FileName, "", "For Your Review", _
"Please see the attached PDF file." _
& vbNewLine & vbNewLine & "Thanks!", False
Else
MsgBox "Not possible to create the PDF, possible reasons:" & vbNewLine & _
"Microsoft Add-in is not installed" & vbNewLine & _
"You Canceled the GetSaveAsFilename dialog" & vbNewLine & _
"The path to Save the file is not correct" & vbNewLine & _
"You didn't want to overwrite the existing PDF if it exist"
End If
End Sub




Option Explicit
'The code below are used by the macros in the other modules
Function Create_PDF(Myvar As Object, FixedFilePathName As String, _
OverwriteIfFileExist As Boolean, OpenPDFAfterPublish As Boolean) As String
Dim FileFormatstr As String
Dim Fname As Variant
Dim sDate As String

'Test If the Microsoft Add-in is installed
If Dir(Environ("commonprogramfiles") & "\Microsoft Shared\OFFICE" _
& Format(Val(Application.Version), "00") & "\EXP_PDF.DLL") <> "" Then

If FixedFilePathName = "" Then
'Open the GetSaveAsFilename dialog to enter a file name for the pdf
FileFormatstr = "PDF Files (*.pdf), *.pdf"
sDate = Replace(Replace(FormatDateTime(Now(), vbShortDate), "/", "."), ":", ".")
'This names the pdf by using 2 fields from the workbook and the date
Fname = ActiveWorkbook.Path & "\" & Sheets("Summary").Cells(9, 2) & " " & ActiveSheet.Cells(1, 1) & " " & Format(sDate, "medium date") & ".pdf"
'If you cancel this dialog Exit the function
If Fname = False Then Exit Function
Else
Fname = FixedFilePathName
End If

'If OverwriteIfFileExist = False we test if the PDF
'already exist in the folder and Exit the function if that is True
If OverwriteIfFileExist = False Then
If Dir(Fname) <> "" Then Exit Function
End If

'Now the file name is correct we Publish to PDF
On Error Resume Next
Myvar.ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=Fname, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=OpenPDFAfterPublish
On Error GoTo 0

'If Publish is Ok the function will return the file name
If Dir(Fname) <> "" Then Create_PDF = Fname
End If
End Function


 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
Hello. Actually that is where I got the code to create the PDF and Email it. I had to play around with it to get the filename and path correct but it is working. But now I'm trying to take that code and modify from save the excel worksheet as a PDF to saving as a new Excel workbook. I tried just changing the extension from pdf to xls but that didn't work, so I tried working with the code in my original email, which works up to the actual save filename command.
 
Upvote 0
I stand corrected! I found the code to save and send Excel. Right now it's saving to a temp directory and deleting. Can someone help me tweak it to use the path and filename I'm using for the pdf: Fname = ActiveWorkbook.Path & "\" & Sheets("Summary").Cells(9, 2) & " " & ActiveSheet.Cells(1, 1) & " " & Format(sDate, "medium date") & ".xls"


Sub Mail_ActiveSheet()
'Working in 2000-2010
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
'Copy the sheet to a new workbook
ActiveSheet.Copy
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 2000-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2010, we exit the sub when your answer is
'NO in the security dialog that you only see when you copy
'an sheet from a xlsm file with macro's disabled.
If Sourcewb.Name = .Name Then
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox "Your answer is NO in the security dialog"
Exit Sub
Else
Select Case Sourcewb.FileFormat
Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
Case 52:
If .HasVBProject Then
FileExtStr = ".xlsm": FileFormatNum = 52
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
Case 56: FileExtStr = ".xls": FileFormatNum = 56
Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
End Select
End If
End If
End With
' 'Change all cells in the worksheet to values if you want
' With Destwb.Sheets(1).UsedRange
' .Cells.Copy
' .Cells.PasteSpecial xlPasteValues
' .Cells(1).Select
' End With
' Application.CutCopyMode = False
'Save the new workbook/Mail it/Delete it
TempFilePath = Environ$("temp") & "\"
TempFileName = "Part of " & Sourcewb.Name & " " _
& Format(Now, "dd-mmm-yy h-mm-ss")
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With Destwb
.SaveAs TempFilePath & TempFileName & FileExtStr, _
FileFormat:=FileFormatNum
On Error Resume Next
With OutMail
.To = ""
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.Body = "Hi there"
.Attachments.Add Destwb.FullName
'You can add other files also like this
'.Attachments.Add ("C:\test.txt")
'.Send 'or use .Display
.Display
End With
On Error GoTo 0
.Close SaveChanges:=False
End With
'Delete the file you have send
Kill TempFilePath & TempFileName & FileExtStr
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,207,090
Messages
6,076,520
Members
446,211
Latest member
b306750

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top