简体   繁体   English

如何在VBA上使用IF条件自动筛选

[英]How to AutoFilter using IF conditions on VBA

I am really new to VBA and I got stuck on a filtering function that I cannot resolve looking online. 我真的是VBA的新手,但是我陷入了无法在线查看的过滤功能。

I basically built a login form which allows different users to see different data on a "Report sheet" once they log in. In the "Report sheet" I have two columns "P" and "Q" in which some names are reported. 我基本上建立了一个登录表单,该表单允许不同的用户登录后在“报告表”上看到不同的数据。在“报告表”中,我有两列“ P”和“ Q”,其中报告了一些名称。

Let's say: 比方说:

P      Q
User1  User2

Paul   Bob
Martin Martin
Bob    Bob
Tom    Martin
Ralph  Bob

I then used this code on VBA: 然后,我在VBA上使用了以下代码:

Private Sub Worksheet_Activate()

Range("Report!$F$6:$Y$11").CurrentRegion.AutoFilter Field:=12, Criteria1:=Range("G3").Value

End Sub

**G3 is the reference cell for the name* ** G3是名称的参考单元格*

Now, if I login with Bob, using that code, the result will be: 现在,如果我使用该代码登录Bob,结果将是:

P      Q
User1  User2

Paul   Bob
Bob    Bob
Ralph  Bob

That is correct! 那是对的! However, if I try to login with Paul, no result is available because he's not on the Field:=12 (column "Q"). 但是,如果我尝试用Paul登录,则没有结果可用,因为他不在Field:= 12(列“ Q”)上。

I would like to do something like this: IF Paul is not on column "Q", stop filtering that column and start filtering column "P". 我想做这样的事情:如果Paul不在“ Q”列上,请停止过滤该列,然后开始过滤“ P”列。

I tried with: 我尝试过:

Private Sub Worksheet_Activate()

If Range("Report!$F$6:$Y$11").CurrentRegion.AutoFilter(Field:=12, Criteria1:=Range("G3").Value) Then 'do nothing

Else
Range("Report!$F$6:$Y$11").CurrentRegion.AutoFilter Field:=11, Criteria1:=Range("G3").Value

End If

End Sub 

but I don't really know what to state for positive results. 但我真的不知道该说些什么来取得积极的结果。

Thank you in advance to everyone that will help me on that. 在此先感谢所有对我有帮助的人。

You can use Find method of range to see if present 您可以使用范围的查找方法来查看是否存在

Option Explicit
Public Sub test()
    Dim found As Range
    Set found = Worksheets("Report!").Range("$Q$6:$Q$11").Find(what:=Range("G3").Value, lookat:=xlWhole)

    If Not found Is Nothing Then
        ' Stuff with Field:=12, Criteria1:=Range("G3").Value)
    Else
      ' Stuff with Field:=11, Criteria1:=Range("G3").Value)
    End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM