[英]VBA code for Emailing active Excel file as pdf or Excel
I have code for a command button to save an active Excel file as pdf and then open it in Outlook for the user to send as an email.我有一个命令按钮的代码,用于将活动的 Excel 文件保存为 pdf,然后在 Outlook 中打开它供用户作为电子邮件发送。
However, this requires the user to save the file as a pdf before it opens it in Outlook.但是,这要求用户在 Outlook 中打开文件之前将文件另存为 pdf。 It works perfectly if the user wants to save a copy to their files.
如果用户想将副本保存到他们的文件中,它可以完美地工作。
What if the user wants to use the submit button but doesn't want to save a copy off and cancels that process?如果用户想使用提交按钮但不想保存副本并取消该过程怎么办? With the code I have below, it just fails out.
使用我下面的代码,它只是失败了。
Is it possible to code it so that if the user decides they don't want to save a copy off, that it will default to send an email with the active excel file attached instead?是否可以对其进行编码,以便如果用户决定他们不想保存副本,它将默认发送附有活动 excel 文件的电子邮件?
Private Sub CommandButton1_Click()
'
Dim OutApp As Object
Dim OutMail As Object
Dim v As Variant
v = Application.GetSaveAsFilename(Range("A4").Value, "PDF Files (*.pdf), *.pdf")
If Dir(v) <> "" Then
If MsgBox("File already exists - do you wish to overwrite it?", vbYesNo, "File Exists") = vbNo Then Exit Sub
End If
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=v, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, From:=1, To:=3, OpenAfterPublish:=False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = ""
.CC = ""
.BCC = ""
.Subject = ""
.Body = ""
.Attachments.Add v
.Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Try the following尝试以下
Option Explicit
Private Sub CommandButton1_Click()
Dim msg As String
msg = "Would you like to save this file as pdf?"
If MsgBox(msg, vbYesNo) = vbYes Then
Dim v As Variant
v = Application.GetSaveAsFilename(Range("A4").Value, _
"PDF Files (*.pdf), *.pdf")
If Dir(v) <> "" Then
If MsgBox("File already exists - do you wish to overwrite it?", _
vbYesNo, "File Exists") = vbNo Then 'Exit Sub
End If
End If
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, fileName:=v, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, From:=1, To:=3, OpenAfterPublish:=False
End With
Else
ActiveWorkbook.Save
v = ActiveWorkbook.path & "\" & ActiveWorkbook.Name
End If
Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")
Dim OutMail As Object
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ""
.CC = ""
.BCC = ""
.Subject = ""
.Body = ""
.Attachments.Add v
.Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.