我希望能够将活动wookbook的副本保存在特定文件夹中,并将该文件作为电子邮件附件发送。我已经准备好文件名了,但是如果有人想更改文件名,我添加了一个输入框,该框在我按取消之前都可以正常工作,只是尝试将文件名保存为“ false”,这是我想要的要做的是退出子菜单,并杀死/关闭复制的工作簿,如果文件未保存,则不显示消息框消息
Sub SaveandSend()
'Working in Excel 97-2016
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 xOutApp As Object
Dim xOutMail As Object
Dim xMailBody As String
On Error Resume Next
Set xOutApp = CreateObject("Outlook.Application")
Set xOutMail = xOutApp.CreateItem(0)
xMailBody = "Body content" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2"
On Error Resume Next
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 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
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 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
DefaultName = Range("a1") & " Time Sheet WEEK END" & " " & Range("A3").Text
'Save the new workbook and close it
TempFilePath = Application.DefaultFilePath & "\"
TempFileName = Application.InputBox("What would you like to name your attachment? (No Special Characters!)", _
"File Name", Type:=2, Default:=DefaultName)
With Destwb
.SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
With xOutMail
.To = ""
.CC = ""
.BCC = ""
.Subject = "Test email send by button clicking"
.Body = xMailBody
.Attachments.Add ActiveWorkbook.FullName
.Display 'or use .Send
End With
On Error GoTo 0
Set xOutMail = Nothing
Set xOutApp = Nothing
.Close SaveChanges:=False
End With
MsgBox "You can find the new file in " & TempFilePath
With Application
.ScreenUpdating = True
.EnableEvents = True
'Clear Memory
Set OutlookMessage = Nothing
Set OutlookApp = Nothing
'Optimize Code
ExitSub:
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayAlerts = True
End With
End Sub