2013-08-29 101 views
-1

所以我有這個自動電子郵件腳本,它一切正常,但我遇到的問題是,當一個電子郵件彈出無效,它會錯誤並退出,我是什麼想知道的是,有沒有辦法告訴它是否有錯誤跳過該記錄並進入下一個記錄?VBScript錯誤消息和處理

Set objMessage = CreateObject("CDO.Message") 
Set app = CreateObject("Excel.Application") 
Set fso = CreateObject("Scripting.FileSystemObject") 

For Each f In fso.GetFolder("##############").Files 
    If LCase(fso.GetExtensionName(f)) = "xls" Then 
    Set wb = app.Workbooks.Open(f.Path) 

set sh = wb.Sheets("Auto Email Script") 
row = 4 
email = sh.Range("A" & row) 
LastRow = sh.UsedRange.Rows.Count 

Const ForReading = 1, ForWriting = 2, ForAppending = 8 
Dim f         
Set f = fso.OpenTextFile("#####################.txt", ForReading)          
BodyText = f.ReadAll 

For r = row to LastRow 
    If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then 
    email = sh.Range("A" & row) 
    sh.Range("I" & row).Value = "Sent" 
     row = row + 1 
    End if 

    If email = "" Then 
    Wscript.Quit 
    End if 

objMessage.Subject = "Billing: Meter Read" 
objMessage.From = "################" 
objMessage.To = email 
objMessage.TextBody = BodyText 

objMessage.Configuration.Fields.Item _ 
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 
objMessage.Configuration.Fields.Item _ 
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "################" 
objMessage.Configuration.Fields.Item _ 
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 

objMessage.Configuration.Fields.Update 
objMessage.Send 

Next 
wb.Save 
f.Close 
Set f = Nothing 
Set fso = Nothing 
wb.Close 
End If 
Next 
+1

在錯誤恢復下? – 2013-08-29 08:31:11

+1

哪一行失敗? objMessage.Send? – Juliusz

+0

你見過http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles? – pnuts

回答

1

它仍然不是很清楚,我你所說的「無效地址」的意思。如果您的意思是格式不正確的地址,您可以驗證它,例如用正則表達式:

Set re = New RegExp 
re.Pattern = "^[a-z0-9][a-z0-9._]*@[a-z][a-z0-9-]*\.[a-z]+$" 
re.IgnoreCase = True 

If re.Test(email) Then 
    'send mail 
End If 

注意,上面的表達式是相當保守,僅涵蓋所有可能的有效地址的安全子集。

如果你的意思是一個地址是由你需要啓用錯誤處理objMessage.Send您的郵件服務器拒絕爲@mehow建議:

On Error Resume Next 
objMessage.Send 
If Err Then WScript.Echo Hex(Err.Number) & ": " & Err.Description 
On Error Goto 0 
+0

你給的第二個選項正是我正在尋找,我到底會把這個放在劇本中?非常感謝! –

+1

用我發佈的代碼段替換這行'objMessage.Send'。 –

+0

好的..非常感謝Ansgar! –