2016-05-13 113 views
2

我試圖用附件發送電子郵件:帶附件..VBA代碼發送電子郵件

我的代碼:

Sub SendEmailUsingGmail() 
Dim Text As String 
Dim Text2 As String 
Dim i As Integer 
Dim j As Integer 
Dim NewMail As CDO.Message 

Set NewMail = New CDO.Message 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True 

'Make SMTP authentication Enabled=true (1) 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 

'Set the SMTP server and port Details 
'To get these details you can get on Settings Page of your Gmail Account 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com" 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 

'Set your credentials of your Gmail Account 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "[email protected]" 

NewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "********" 

'Update the configuration fields 
NewMail.Configuration.Fields.Update 

'Set All Email Properties 

With NewMail 
    .Subject = "Test Mail" 
    .From = "[email protected]" 
    For i = 1 To 2 
     Text = Cells(i, 1).Value 
     Text2 = Cells(i, 2).Value 
     .To = Text 
     .BCC = "" 
     .TextBody = "" 
     .AddAttachment Text2 
     Text2 = Null 
     .Send 
    Next i 

End With 

End Sub 

它讀取從第一欄和第二欄我的電子郵件地址共享附件的地址。 當它通過電子郵件發送最後一個用戶時,它將所有附件從最上面一行附加到附件上。 e.g:

[email protected] C:\Users\sprasad\Desktop\Test.docx   
[email protected]  C:\Users\sprasad\Desktop\Test2.docx 

所以對於SHA @ GWU它會發出兩個文檔測試和Test2的。

我只想附加sha @ gwu的test2文檔。 我的代碼怎麼了?

+1

你'結束With'和'接下來i'是走錯了路周圍 –

+0

@Macro ...你可以PLZ解釋...我是新來的VBA和這是我的第三個代碼.... – Shank

+0

我不知道什麼是要解釋 - 交換'結束與'和'下一個我... ...因爲它代表應該代碼shouldn甚至不會編譯,所以不知道你如何運行它。 –

回答

0

加入這一行...

With NewMail 
    .Subject = "Test Mail" 
    .From = "[email protected]" 
    For i = 1 To 2 

    Text = Cells(i, 1).Value 
    Text2 = Cells(i, 2).Value 
    .To = Text 
    .BCC = "" 
    .TextBody = "" 
    .Attachments.DeleteAll  ' <-------- 
    .AddAttachment Text2 
    Text2 = Null 
    .Send 
    Next i 

End With 

End Sub 
0

改成這樣

For i = 1 To 2 

Set NewMail = New CDO.Message 

'// Rest of code here... 

With NewMail 
    .Subject = "Test Mail" 
    .From = "[email protected]" 

    Text = Cells(i, 1).Value 
    Text2 = Cells(i, 2).Value 
    .To = Text 
    .BCC = "" 
    .TextBody = "" 
    .AddAttachment Text2 
    Text2 = Null 
    .Send 

End With 

Next 
+0

這工作.... thnx – Shank

+0

不要忘了標記爲答案,如果它通過點擊左邊的勾號幫助 –