VBA - 从嵌套查询创建过滤条件

时间:2012-10-10 09:17:55

标签: vba if-statement nested

我正在尝试创建一个检查数据的过滤条件,如果匹配则会打印数据。 我有以下,我得到类型不匹配错误。对于cTest。 我也尝试了以下(没有引号 - 但它返回false):cTest =(InStr(getName(iVar),a1)> 0)

是否有更简单的方法来创建过滤条件。

如果标准中填写了字段a1,a2和a3,则应在返回任何内容之前检查该值是否包含所有字段。

  Dim cTest As Variant

If a1 <> "" Or a2 <> "" Or a3 <> "" Then
If a1 <> "" Then
  If a2 <> "" Then
   If a3 <> "" Then
   'Value entered in 1,2,3
    cTest = "(InStr(getName(iVar), a1) > 0) And (InStr(getName(iVar), a2) > 0) And (InStr(getName(iVar), a3) > 0)"
    End If
    ' Value entered in 1,2
    cTest = "(InStr(getName(iVar), a1) > 0) And (InStr(getName(iVar), a2) > 0)"
      End If
      '(Value entered in 1 only
   cTest = "(InStr(getName(iVar), a1) > 0)"
ElseIf a2 <> "" Then
  If a3 <> "" Then
    'Value entered in 2,3
    MsgBox ("2nd, 3rd value entered")
  End If
   ' Value entered in 2 only
ElseIf a3 <> "" Then
    'Value entered in 3 only
     MsgBox ("3rd value entered")
Else
     ' no value entered
     MsgBox ("no value entered")
End If
End If

For iVar = 1 To Phrases.MaxIndex()


        If (cTest) Then
        'We want this one
        .Cells(irow, 1).Value = getName(iVar)
        irow = irow + 1
      End If
    Next iVar

  End With

1 个答案:

答案 0 :(得分:0)

如何使用简单的AND&amp; amp; OR条件?

Sub testing()

    If ((a1 <> "" And InStr(getName(iVar), a1) > 0) Or a1 = "") And _
    ((a2 <> "" And InStr(getName(iVar), a2) > 0) Or a2 = "") And _
    ((a3 <> "" And InStr(getName(iVar), a2) > 0) Or a3 = "") Then
        ' the wanted one
    End If

End Sub