VBA在电子邮件的HTMLBody中生成行,具体取决于具有值的行数

时间:2014-03-06 16:21:01

标签: excel vba excel-vba

所以我得到了订购语句的请求,我有一个自动命令它们的宏,但现在我希望同一个宏在最后发送电子邮件。我处于70%的解决方案,但我陷入了一个关键部分。我没有得到一些固定的数字或声明,每天订购它的2天20。

问题:如何在电子邮件正文中生成一行文本,具体取决于具有值的行数。

这是我到目前为止所做的:

Sub Email()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim Email As String
    Dim ws As Worksheet
    Set ws = Worksheets("Data")
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    K = 2
    Do While ws.Cells(K, 1) <> "" ' While column A has cells with data do
' this matches 'Name Of' & cell value and puts it in column E (E1=Name of Joe)
      ws.Cells(K, 5) = "Name Of " & ws.Cells(K, 1).Value  

        K = K + 1
    Loop

    Email = "Hello, <br><br>" & _
            "The following Statements were ordered today: <br><br>" & _
     '===================================================================
                 "<br>" & ws.Cells(k, 5).Value & _
      ' I am trying to get this line to be generated depending on how many 
      ' rows have data in column A so if there are 5 names there are 5 lines
      '==================================================================
                       "<br><br> Thank you." & _
                       "<br><br><br> <i> Call if you have any questions </i>"

    With OutMail
        .to = "me@me.com"
        .CC = ""
        .BCC = ""
        .Subject = "Statements Ordered"
        .HTMLBody = Email

        .Send
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

所以我希望替换"<br>" & ws.Cells(k, 5).Value & _行,因为由于K的最后一个值,它只生成包含数据的最后一行。

我试图插入do while ws.cells(k, 1) <> "",但没有Joy可以使用它。我开始研究创建自己的功能,但这是我的想法。

澄清:

当前的电子邮件看起来像这样

Hello,

The following Statements were ordered today:

Name of Joe
Name of Bob
Name of Billy

Thank you.

Call if you have any questions.

我要做的是让VBA查看A列并查看有多少行数据并生成行Name of & the value of the cell

我还在代码中添加了注释。

1 个答案:

答案 0 :(得分:1)

这将遍历第5列中的所有内容,并将所有数据放入变量'myvalue'。

这应该足以让你入门。

btm = ws.Cells(Rows.Count, 5).End(xlUp).Row
for i = 1 to btm
    myvalue = myvalue & "<br>" & ws.Cells(i, 5).Value
next i

Email = "Hello, <br><br>" & _
                "The following Statements were ordered today: <br><br>" & _
                        "<br>" & myvalue & _
                   "<br><br> Thank you." & _
                   "<br><br><br> <i> Call if you have any questions </i>"