[英]Send sheet via email
我有一個名為狀態報告的工作簿,其中包含幾張工作表。 我需要通過 email 發送sheet8(稱為表) 。
我生成了代碼,但它給了我錯誤。
文件的位置在桌面上。
Option Explicit
Sub EmailWithOutlook()
Dim oApp As Object
Dim oMail As Object
Dim WB As Workbook
Dim FileName As String
Dim wSht As Worksheet
Dim shtName As String
Application.ScreenUpdating = False
ActiveSheet.Copy
Set WB = ActiveWorkbook
FileName = WB.Worksheets(1).Name
Kill "C:\Users\Default\Desktop" & "Status report.xlsm"
On Error GoTo 0
WB.SaveAs FileName:="C:\Users\Default\Desktop" & "Status report.xlsm"
Set oApp = CreateObject("Outlook.Application")
Set oMail = oApp.CreateItem(0)
With oMail
.To = "sleepyyx@gmail.com"
.Subject = "Test workbook"
.body = "Hello, could you please check workbook" & vbCrLf & vbCrLf & _
"I attached you file"
.Attachments.Add WB.FullName
.Display
End With
WB.ChangeFileAccess Mode:=xlReadOnly
Kill WB.FullName
WB.Close SaveChanges:=False
Application.ScreenUpdating = True
Set oMail = Nothing
Set oApp = Nothing
End Sub
在Kill "C:\Users\Default\Desktop\" & "Status report.xlsm"
中殺死文件之前,您需要檢查文件是否存在:
~~> 檢查文件是否存在
If Dir("C:\Users\Default\Desktop\" & "Status report.xlsm") <> "" Then
Kill "C:\Users\Default\Desktop\" & "Status report.xlsm"
End If
你忘記了反斜杠
您可能正在嘗試使用單元格中的Filename
。
考慮使用變量以保持一致性,以防它發生變化,並確保在路徑和文件名之間包含反斜杠。
FileName = WB.Worksheets(1).Name
Dim sFullFile As String
sFullFile = "C:\Users\Default\Desktop\" & FileName
If Dir(sFullFile) <> "" Then Kill sFullFile
WB.SaveAs FileName:=sFullFile
另外需要注意的是,如果您將其保存為 XLSM,那么原始格式也必須是 XLSM,否則如果您不指定文件格式,SaveAs 將出錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.