2016-12-16 88 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