VBA 遍历行但无法排除前一行内容

VBA Loop through rows but fails to exclude previous row contents

我有以下循环,它从第二行开始为工作表中使用的每一行发送电子邮件。

循环本身有效,它会为从第二行开始的每一行发送电子邮件。

但是,我的循环未能排除前一行的内容并将它们累积到下一行的每一封电子邮件中。我怀疑这与我的单元格引用有关。如果您能提供帮助,那就太好了 :)。

 Sub TestEmail1()
  Application.ScreenUpdating = False

  Dim aOutlook As Object
  Dim aEmail As Object
  Dim rngeAddresses As Range, rngeCell As Range, strRecipients As String
  Dim ccAddresses As Range, ccCell As Range, ccRecipients As String
  Dim rngeSubject As Range, SubjectCell As Range, SubjectContent As Variant
  Dim rngeBody As Range, bodyCell As Range, bodyContent As Variant
  Dim Table1 As Range
  Dim i As Integer

  Set rng = ActiveSheet.UsedRange
  LRow = rng.Rows.Count
    For i = 2 To LRow
      Set Table1 = Worksheets(1).Range("K1:R1")
      Set Table2 = Worksheets(2).Range("K" & i & ":" & "R" & i)
      Set aOutlook = CreateObject("Outlook.Application")
      Set aEmail = aOutlook.CreateItem(0)

      'set sheet to find address for e-mails as I have several people to
      'mail to

      Set rngeAddresses = ActiveSheet.Range("B" & i)
        For Each rngeCell In rngeAddresses.Cells
        strRecipients = strRecipients & ";" & rngeCell.Value
        Next

     Set ccAddresses = ActiveSheet.Range("C" & i)
       For Each ccCell In ccAddresses.Cells
       ccRecipients = ccRecipients & ";" & ccCell.Value
       Next

     Set rngeSubject = ActiveSheet.Range("D" & i)
       For Each SubjectCell In rngeSubject.Cells
       SubjectContent = SubjectContent & SubjectCell.Value
      Next

     Set rngeBody = ActiveSheet.Range("E" & i)
      For Each bodyCell In rngeBody.Cells
       bodyContent = bodyContent & bodyCell.Value
      Next

     'set Importance
     'aEmail.Importance = 2

      'Set Subject
       aEmail.Subject = rngeSubject
     'Set Body for mail
    'aEmail.Body = bodyContent
    aEmail.HTMLBody = bodyContent & "<br><br><br>" & RangetoHTML_    (Table1)            
    aEmail.To = strRecipients
    aEmail.CC = ccRecipients
    aEmail.Send

   Next i

  Exit Sub

 End Sub

是的,您在 SubjectContent、bodyContent 和其他类似变量中积累了越来越长的字符串。每次通过 For i = 2 到 lRow 循环时,都会将当前行中指定单元格的值添加到关联的 Content 变量中。

出于某种原因,您还为每个电子邮件区域设置了一个内部循环,例如 For Each bodyCell in rgneBody.Cells。如果我正确阅读了您的代码 none,则需要这些循环。

所以,考虑到以上情况,我会改变:

Set rngeBody = ActiveSheet.Range("E" & i)
  For Each bodyCell In rngeBody.Cells
  bodyContent = bodyContent & bodyCell.Value
Next

至:

bodyContent = ActiveSheet.Range("E" & i)

如果您认为可读性更好,可以使用中间变量 rngeBody,但这不是必需的。

对您的其他电子邮件区域变量重复上述操作。