2015-03-25 34 views
1

我正在實現一個宏,它檢查E列日期是否與當前日期相距7天。用於多個匹配單元格檢測的宏

如果細胞日期 - 當前日期= 7

然後發送包含具有匹配單元格的行的電子郵件。 這是我的代碼,它成功的工作,除了一個問題。

Sub Workbook_Open() 

Dim rngStart As Range 
Dim rngEnd As Range 
Dim rngCell As Range 
Dim strHtmlHead As String 
Dim strHtmlFoot As String 
Dim strMsgBody As String 
Dim strMsgBody1 As String 
Dim strMsg As String 
Dim objEmail As Object 
Dim OutlookApp As Object 
Dim OutlookMail As Object 

'On Error GoTo ErrHnd 

'only run if between midnight and 2AM 
'If Hour(Now) < 2 Then 

'setup basic HTML message header and footer 


'setup start of body of message 
strMsgBody = "The following task(s) are due in less than 7 days :" 

'Worksheet name 
With Worksheets("Sheet1") 
    'set start of date range 
    Set rngStart = .Range("E1") 
    'find end of date range 
    Set rngEnd = .Range("E" & CStr(Application.Rows.Count)).End(xlUp) 

    'loop through all used cells in column G 
    For Each rngCell In .Range(rngStart, rngEnd) 
     'test if date is equal to 7 days from today 
     If IsDate(rngCell.Value) Then 
     If rngCell.Value - Int(Now) = 7 Then 
      'add to message - use task name from column A (offset -3) 
      'change as required 
      strMsgBody1 = strMsgBody & "<Br>" & "<Br>" & "Task: " & rngCell.Offset(0, -3).Text _ 
       & " is due on " & rngCell.Text & "<Br> " & "<Br> " & "Therefore please take necessary action" 
     End If 
     End If 
    Next rngCell 

    'Note last test time/date 
    rngEnd.Offset(1, -3) = Now 
    rngEnd.Offset(1, -3).NumberFormat = "dd/mm/yy" 
End With 

'put message together 
strMsg = strMsgBody1 

'test message 
'MsgBox strMsg 

'create the e-mail object 


Set OutlookApp = CreateObject("Outlook.Application") 
Set OutlookMail = OutlookApp.CreateItem(0) 

With OutlookMail 

.To = "[email protected]" 
.CC = "" 
.BCC = "" 
.Subject = "Task Alert" 
.HTMLBody = strMsg 
.Send 
End With 


Set OutlookMail = Nothing 
Set OutlookApp = Nothing 

Application.DisplayAlerts = True 
Application.ScreenUpdating = True 


'remove the e-mail object 

Exit Sub 

'error handler 
ErrHnd: 
Err.Clear 

End Sub 

當有兩個或多個記錄與相匹配的標準

細胞日期相同的日期 - = 7

那麼只有一個記錄顯示在電子郵件和發送到當前日期電子郵件地址。

例如有三個記錄,如下所示:

enter image description here

並且僅在檢測到第三記錄和附加到電子郵件的正文。

我需要知道爲什麼會發生這種情況? 如何編輯我的代碼以糾正此問題?

回答

1

要解決問題,請刪除strMsgBody1聲明並用strMsgBody替換每個發生的項。你不需要第二個變量。

+0

謝謝, 它完美的作品 – adrian 2015-03-25 06:58:55

相關問題