0

我有一个脚本可以自动通过电子邮件发送存储在 Excel 中的地址列表,但它只发送到第一个地址而不循环到其余地址,我似乎无法修复它:

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

For Each f In fso.GetFolder("Y:\Billing_Common\autoemail").Files
  If LCase(fso.GetExtensionName(f)) = "xls" Then
    Set wb = app.Workbooks.Open(f.Path)

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

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim f                                   
Set f = fso.OpenTextFile("Y:\Billing_Common\autoemail\Script\Email.txt", ForReading)                                        
BodyText = f.ReadAll

For r = row to LastRow
    If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then 
    objMessage.Subject = "Billing: Meter Read" 
    objMessage.From = "billing@energia.ie"
    row = row + 1
    objMessage.To = email
    objMessage.TextBody = BodyText

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


'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "SERVER ADDRESS HERE"

'Server port
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 

objMessage.Configuration.Fields.Update
objMessage.Send

    End if
Next

f.Close
Set f = Nothing
Set fso = Nothing
wb.Close
End If
Next

任何帮助将不胜感激!

谢谢!

4

1 回答 1

2
row = 2
email = sh.Range("A" & row)
...
For r = row to LastRow
  ...
  objMessage.To = email
  ...
Next

您设置email为单元格的值"A2"并且从不更改它。如果您想将邮件发送给多个收件人,您应该这样做

objMessage.To = sh.Range("A" & r).Value

或(更好)建立一个收件人列表(假设您使用的范围从第一个表格行中的标题开始):

ReDim recipients(LastRow - row)
For r = row To LastRow
  recipients(r - row) = sh.Range("A" & r).Value
Next
objMessage.To = Join(recipients, ";")

并且只发送一次消息。MTA 将处理其余部分。


旁注:正如 Vishnu Prasad Kallummel 在评论中指出的那样,您的代码不会关闭它启动的 Excel 实例。与在 VBScript 中创建的其他对象不同,Office 应用程序不会自动终止脚本,因此您必须自己处理它:

...
wb.Close
app.Quit
于 2013-07-03T10:26:48.600 回答