2017-06-14 77 views
0

我試圖從活動電子表格中的單元格中繪製可編輯的輸入。我設法在Outlook中生成電子郵件並附加多個文件。將多個文件附加到循環中的Outlook電子郵件中

問題是,不是通過每個單元格與數據(和不同的目錄輸入)循環,從而附加「x」數量的單個文件,而是附加相同的文件「x」次。

Option Explicit 

Sub TESTCreateEmail() 


    'define variables for outlook 
    Dim olApp As Outlook.Application 
    Dim olMail As Outlook.MailItem 

    'define variables for attachements to email 
    Dim wb As Workbook 
    Dim ws As Worksheet 
    Dim LoopAttach As Integer 
    Dim x As Integer 
    Dim y As Integer 

    x = Range("E9", Range("E100").End(xlUp)).Count 

    'set parameters for outlook 
    Set olApp = New Outlook.Application 
    Set olMail = olApp.CreateItem(olMailItem) 

    'set parameters for attachements to email 
    Set wb = ThisWorkbook 
    Set ws = wb.Application.ActiveSheet 

    'create email 
    With olMail 

     .To = ws.Range("H9") 
     .CC = ws.Range("I9") 
     olMail.SentOnBehalfOfName = "[email protected]" 
     olMail.Recipients.ResolveAll 
     .BodyFormat = olFormatHTML 

     olMail.HTMLBody = "<html><p><font face=""Calibri""><font size=3>Dear Sir/ Madam,</p>" 

     'loop to attach multiple files 
     For LoopAttach = 1 To x 
      .Attachments.Add ws.Range("E9").Offset(x - 1, 0) _ 
      & ws.Range("F9").Offset(x - 1, 0) 
     Next LoopAttach 

     .Display 

    End With 

End Sub 

Examples of Excel input and resulting Outlook email

回答

0

在代碼變量x值保持在執行循環期間相同。這就是爲什麼每次執行循環時都附加相同的文件。

試試這個

For LoopAttach = x To 1 Step -1 
     .Attachments.Add ws.Range("E9").Offset(LoopAttach - 1, 0) _ 
     & ws.Range("F9").Offset(LoopAttach - 1, 0) 
    Next LoopAttach 
+0

我不能夠感謝你! – Jimmy

0

這是簡單的錯誤 - x是用於循環一定的限度。您需要使用LoopAttach變量而不是x

For LoopAttach = 1 To x 
    .Attachments.Add ws.Range("E9").Offset(LoopAttach - 1, 0) _ 
    & ws.Range("F9").Offset(LoopAttach - 1, 0) 
Next LoopAttach 
+0

我不能夠感謝你! – Jimmy

相關問題