VBA:根据其他列的值

时间:2016-12-16 09:48:56

标签: excel vba

首先,我想知道这封信是否是" A" A列中包含,其次如果B列中至少有一个出现1,则为

Column A   |  Column B
   A       |     0
   B       |     1
   A       |     1
   C       |     0
   A       |     0

凭借我糟糕的技能,我几乎不知道专栏中是否有这样的价值。

Set Obj = Sheets("Sheet 1").Range("Column A")
    If Not IsError(Application.Match("A", ObjColumn, 0)) Then MsgBox("There is at least one occurrence")
        If Application.Vlookup("A", ObjTable, 2, False) = 1 Then MsgBox("At least one A has 1 as value")

不幸的是,Application.Vlookup我只能探索首次出现的价值。

我做了一些研究,但我刚刚发现这个简单问题的代码过于复杂。

提前谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用WorksheetFunction.CountIf()WorksheetFunction.CountIfs()

Sub main()
    With Sheets("Sheet 1") '<--| reference your sheet
        If Application.WorksheetFunction.CountIf(.Columns(1), "A") > 0 Then
            MsgBox ("There is at least one occurrence")
            If Application.WorksheetFunction.CountIfs(.Columns(1), "C", .Columns(2), 1) > 0 Then MsgBox ("At least one A has 1 as value")
        End If
    End With
End Sub

或者,如果您在第一行有标题,则可以使用AutoFilter()Find()方法:

Option Explicit

Sub main()
    With Sheets("Sheet 1") '<--| reference your sheet
        With Intersect(.Range("A:B"), .UsedRange) '<--| reference its columns A and B used cells
            .AutoFilter Field:=1, Criteria1:="A" '<--| filter referenced cells on its 1st column (i.e. column "A") with value "A"
            If Application.WorksheetFunction.Subtotal(103, .Resize(, 1)) > 1 Then '<--| if any cell filtered other than header
                MsgBox ("There is at least one occurrence")
                If Not .Resize(.Rows.count - 1, 1).Offset(1, 1).SpecialCells(xlCellTypeVisible).Find(what:=2, LookIn:=xlValues, lookat:=xlWhole) Is Nothing Then MsgBox ("At least one A has 1 as value") '<--|search 2nd column filtered cells for "1")
            End If
        End With
    End With
End Sub

答案 1 :(得分:0)

谢谢@ user3598756

您的建议帮助我找到了满足我需求的解决方案,因为我有第三列空白也会激活代码。

Column A   |  Column B  |  Column C
   A       |     0      |    ""
   B       |     1      |    0
   A       |     0      |    1
   C       |     1      |    ""
   A       |     0      |    ""

以下是代码的一部分:

    Set Obj1 = Sheets("Sheet 1").Range("Table[Column A]")
    Set Obj2 = Sheets("Sheet 2").Range("Table[Column B]")
    Set Obj3 = Sheets("Sheet 3").Range("Table[Column C]")
        If Not IsError(Application.Match("A", Obj1, 0)) Then
            If Application.CountIfs(Obj1, "A", Obj2, "1") Or Application.CountIfs(Obj1, "A", Obj3, "<>") > 0 Then MsgBox ("At least one occurrence has either an 1 in B or an empty field in C.")
End If

非常感谢!