如何在Excel中的列中处理多个IFTHEN查询?

时间:2013-11-07 10:36:29

标签: excel excel-vba vba

我正在尝试创建一个分配系统,虽然我已经编程VBA,但这次我被卡住了!

我有五列的数据,其中的内容决定了我分配给他们的工作人员。

我需要做的是:

If column E = "a", then put name "xx" in column A (of same row)
If column E = "b", then put name "yy" in column A (of same row)
If column E is blank, then move to next criteria....

If column D is "c" then put name "zz" in column A (of same row)
If column D is "d" then move to next criteria....

If column A is blank then put name "ww" in column A.

提前致谢!!

2 个答案:

答案 0 :(得分:0)

Sub Allocate()

    Dim i As Long

    For i = 1 To Range("E" & Rows.Count).End(xlUp).Row
        If Range("E" & i) = "a" Then
            Range("A" & i) = "xx"
        ElseIf Range("E" & i) = "b" Then
            Range("A" & i) = "yy"
        End If

        If Range("D" & i) = "c" Then
            Range("A" & i) = "zz"
        End If

        If IsEmpty(Range("A" & i)) Then
            Range("A" & i) = "ww"
        End If
    Next i

End Sub

请注意

If column E is blank, then move to next criteria....

不包含在代码中的任何位置,在代码中实现这一点没有意义,因为它确实没有:)

答案 1 :(得分:0)

就像我在你提问的链接中提到的那样,你不需要循环。

如果您使用Excel公式,那么您将使用类似

的内容
=IF(E1="a","xx",IF(E1="b","yy",IF(D1="c","zz","ww")))

只需在vba代码中使用

Option Explicit

Sub Sample()
    Dim lRow As Long

    '~~> Change this to the relevant sheet
    With ThisWorkbook.Sheets("Sheet1")
        lRow = .Range("E" & .Rows.Count).End(xlUp).Row

        .Range("A1:A" & lRow).Formula = "=IF(E1=""a"",""xx"",IF(E1=""b"",""yy"",IF(D1=""c"",""zz"",""ww"")))"

        .Range("A1:A" & lRow).Value = .Range("A1:A" & lRow).Value
    End With
End Sub

<强>截图

enter image description here