将工作簿中的特定工作表发送到工作表中存储的指定电子邮件

时间:2018-09-19 05:28:45

标签: excel-vba

我写了一个代码,用于发送工作表中任意一张带有附件的sheet5中存储的电子邮件。当工作表的名称与A列中的值匹配时,应从B列中选择电子邮件并以相同的名称附加工作表。

For Each sh In ThisWorkbook.Worksheets

    Dim i As Integer

    While (Sheet5.Cells(1, i) <> vbNullString)

    If (sh.Name = Sheet5.Range("a" & i).Value) Then
        sh.Copy
        Set wb = ActiveWorkbook

        TempFileName = "Sheet " & sh.Name & " of " _
                     & ThisWorkbook.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")

        Set OutMail = OutApp.CreateItem(0)

        With wb
            .SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum

            On Error Resume Next
            With OutMail
                .To = Sheet5.Range("b" & i).Value
                .CC = Sheet5.Range("c" & i).Value
                .BCC = ""
                .Subject = "This is the Subject line"
                .Body = "Hi there"
                .Attachments.Add wb.FullName
                .Display
            End With
            On Error GoTo 0

            .Close savechanges:=False
        End With

        Set OutMail = Nothing

        Kill TempFilePath & TempFileName & FileExtStr
End If

Wend

Next sh
  

'while循环时我出错,而(Sheet5.Cells(1,i)<>   vbNullString)”和在If语句中“ If(sh.Name = Sheet5.Range(“ a”&   i).Value)然后“

请指导

1 个答案:

答案 0 :(得分:0)

如果所显示的代码完整,则i没有值将默认为0。您声明引用i的任何范围都将出错,因为没有行或列索引相等到0。

您需要给i赋予大于0的值