2016-03-25 56 views
0

我是新來的宏。 我需要excel發送電子郵件AUTOMATICALLY每當到期日期臨近。 (例如大約15天前)。到目前爲止,我已經將電子郵件發送給所有人,而不考慮執行日期或條件格式。在VBA 2013中自動發送電子郵件

Dim myApp As Outlook.Application, mymail As Outlook.MailItem 
     Dim mydate1 As Date 
     Dim mydate2 As Long 
     Dim datetoday1 As Date 
     Dim datetoday2 As Long 

Dim x As Long 
With Sheet1 

     Lastrow = .Cells(Rows.Count, 1).End(xlUp).Row 
     For x = 2 To Lastrow 

     mydate1 = Cells(x, 6).Value 
     mydate2 = mydate1 

Cells(x, 10).Value = mydate2 

     datetoday1 = Date 
     datetoday2 = datetoday1 

Cells(x, 9).Value = datetoday2 

     If mydate2 - datetoday2 >= 15 Then 

End If 

    'Cells(x, 8).Font.Bold = 「Send」 
    Cells(x, 8).Interior.ColorIndex = 3 
    Cells(x, 8).Font.ColorIndex = 1 
    Cells(x, 8).Font.Bold = True 
    Cells(x, 8).Value = datetoday2 - mydate2 

     Dim olApp As Outlook.Application 
     Dim olEmail As Outlook.MailItem 

     Set olApp = New Outlook.Application 
     Set olEmail = olApp.CreateItem(olMailItem) 
     olEmail.To = Cells(, 5).Value 

With olEmail 

     .BodyFormat = olFormatHTML 
     '.Display 
     .HTMLBody = "<h1>Hej </h1><br> Detta är ett mail som du ska läsa" & "<br>" & .HTMLBody 
     .Subject = "Möte" 
     .BCC = Cells(x, 5).Value 

     '.send 
End With 

Next 
     Set myApp = Nothing 
     Set mymail = Nothing 
End With 

End Sub 

回答

0

你,你正在測試兩個日期之間的差異線:

If mydate2 - datetoday2 >= 15 Then 

我會假設,如果該日期成功,那麼你要發送的電子郵件。 (我希望我對這個假設是錯誤的,對特定天數的測試需要比這更好),所以你希望你的電子郵件發送代碼在if..then行之後和End如果。然而,你立即遵循if ...然後用End If。

你需要把結束時,如果低了下去:

If mydate2 - datetoday2 >= 15 Then 

    'Cells(x, 8).Font.Bold = 「Send」 
    Cells(x, 8).Interior.ColorIndex = 3 

    ' Code missed out here for clarity & brevity. 

    With olEmail 
     .BodyFormat = olFormatHTML 
     '.Display 
     .HTMLBody = "<h1>Hej </h1><br> Detta är ett mail som du ska läsa" & "<br>" & .HTMLBody 
     .Subject = "Möte" 
     .BCC = Cells(x, 5).Value 

     '.send 
    End With 

End If ' Here is the end if from above 
Next 

再回到你需要實際測試中,你應該使用DateDiff函數:

Dim d1 As Date 
Dim d2 As Date 
Dim days As Long 

d1 = CDate("1 Jan 2016") 
d2 = CDate("16 Jan 2016") 

days = DateDiff("d", d2, d1) ' days is -15 
days = DateDiff("d", d1, d2) ' days is +15 

If days = 15 Then 

    ' send email code 

End If 

乾杯 -

+0

'mydate2 - datetoday2> = 15'正常工作。日期被存儲爲雙數,整數值等於天數,所以如果你關心的只有幾天,它們可以像這樣被添加和減去。如果有的話,OP投到Long是多餘的 - 他們只丟棄存儲在小數點右邊的時間值。 – Comintern

+0

我知道。我想介紹一個有用的函數,它也消除了小數。隨着日期扣除他的測試變得> = 15 & < 16;與datediff它是= 15更自然地讀取我。風格是個人的東西:) –

+0

我假設'>'是爲了某個目的 - 例如說明由於代碼沒有每天運行而錯過了最後期限。就像你說的「風格是個人的東西」,但我通常會發現1行代碼比5更清晰,更易讀,並且數學運算符比記住函數調用的參數順序更具可讀性。 – Comintern