2016-12-16 94 views
0

首先,我想知道列A中是否包含字母“A”,其次是列B中是否有至少一个出现1的情况。VBA:根据其他列的值查找出现次数

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我只能探索第一次出现的价值。

我已经做了一些研究,但我刚刚发现这样一个简单的问题极其复杂的代码。

预先感谢您!

+0

使用'Match'查找列A中存在“A”的行。匹配返回第一个行号,所以您可以检查'If Range(MatchRow,“B”)。Value = 1 Then',这就是它。我相信你可以在互联网上找到很多地方和例子来看看如何使用'Match'。 –

回答

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 
+0

或他可以用你的方式做到;) –

+0

@ShaiRado,我必须停下来! – user3598756

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 

非常感谢!

+0

不客气。很高兴你做到了。然后,您可能想要将我的答案标记为已接受。谢谢! – user3598756

+0

当然,接受!再次感谢您的时间 – Senzar