循环遍历单元格,使用VBA将符合条件的条件添加到列表/字符串中?

时间:2015-07-03 21:33:38

标签: excel vba email excel-vba excel-2013

我是VBA的新手(并且只接受过一些java培训),并且已经碰壁了。

最终目标是循环一系列包含名称的单元格,将相邻单元格的值与常量进行比较。如果满足条件,则应将原始单元格添加到将由另一个负责起草电子邮件的公式摄取的列表中。这将每天重复,并且与每个名称重合的值将会改变。

我已经想出如何使用一个变量来循环遍历范围,该变量将每个名称添加到" TO"电子邮件草稿的一行,但不知道如何为周期添加条件,因此它只添加所需的条件。 基本上,我相信我唯一需要帮助的是" sTo"变量。谢谢!

Sub Draft_Email()

Dim emailRng As Range, cl As Range
Dim adjCellRng As Range, cmp As Range

Dim sTo As String
Dim day As String
Dim EmailBody As String
Dim i As Integer
Dim k As String

k = 85

day = Format(Date, "dddd mmmm d")
EmailBody = "Blah Blah"

Set emailRng = Worksheets("Briefing Order").Range("D4:D31,G4:G31,J4:J31,M4:M31")

For Each cl In emailRng
    **cmp = cl.Offset(0, -1)**
    If cmp >= k Then
        sTo = sTo & ";" & cl.Value & "WindTemp-DG@wnco.com"
    End If
Next cl

sTo = Mid(sTo, 2)

'..Draft Email where .BCC = sTo

End Sub

2 个答案:

答案 0 :(得分:1)

Set emailRng = Worksheets("Briefing Order").Range("D4:D31,G4:G31,J4:J31,M4:M31")
Set adjCellRng = Worksheets("Briefing Order").Range("E4:E31,H4:H31,K4:K31,L4:L31")

'something like the following... 
For i = 1 to emailRng.size 'whatever the limit variable is 
    cl = emailRng(i)
    cmp = adjCellRng(i)
    if cmp==k then
         sTo = sTo & ";" & cl.Value & "Department@work.com"
    end if
Next

sTo = Mid(sTo, 2)

答案 1 :(得分:0)

我会用

更改jdl代码
Set emailRng = Worksheets("Brifing Order").Range("D4:D31,G4:G31,J4:J31,M4,M31")

'something like the following... 
For each c1 in emailRng.cells 
    cmp = c1.offset(0,1)
    if cmp==k then
         sTo = sTo & ";" & cl.Value & "Department@work.com"
    end if
Next

sTo = Mid(sTo, 2)