【问题标题】:filter a table by combination of selected cell values using VBA - syntax error使用 VBA 通过选定单元格值的组合过滤表格 - 语法错误
【发布时间】:2016-08-09 09:26:24
【问题描述】:

你能帮我写下下面的代码吗,我一直收到语法错误

宏的目标是在同一列下通过多行选择进行过滤。

我遇到语法错误的行是:

sColumn(n) = sColumn(n) & _
If(sColumn(n) vbNullString, ",", "") & oCell.Text


If sColumn(n) vbNullString Then

完整代码如下:

Sub combinationFilter()

Dim oRange As Range
Dim oArea As Range
Dim oCell As Range
Dim oLO As ListObject
Dim sColumn() As Variant
Dim n As Long

' Create Filter
Set oLO = Selection.ListObject

If Not oLO Is Nothing Then

    ReDim sColumn(1 To oLO.ListColumns.Count)

    Set oRange = Intersect(Selection, oLO.DataBodyRange)

    For Each oArea In oRange.Areas
        For Each oCell In oArea.Cells
            n = oCell.Column - oLO.Range.Column + 1
            sColumn(n) = sColumn(n) & _
            IIf(sColumn(n) vbNullString, ",", "") & oCell.Text
        Next oCell
    Next oArea

    ' Apply Filter
    For n = LBound(sColumn) To UBound(sColumn)
        If sColumn(n) like vbNullString Then
            oLO.Range.AutoFilter _
            Field:=n, _
            Criteria1:=Split(sColumn(n), ","), _
            Operator:=xlFilterValues
        End If
    Next n

End If

End Sub

我还在以下几行中收到不匹配错误:

If sColumn(n) like vbNullString Then
oLO.Range.AutoFilter _
Field:=n, _
Criteria1:=Split(sColumn(n), ","), _
Operator:=xlFilterValues

提前谢谢你。

【问题讨论】:

  • 您能否通过适当的语法缩进编辑以使您的代码可读?
  • @SamGilbert - 我认为<>(不是=)被markdown吞没了。

标签: vba excel syntax-error


【解决方案1】:

根据您的情况,正确的语法可能如下所示:

sColumn(n) = sColumn(n) & IIf(IsNull(sColumn(n)), "", ",") & oCell.Text

或者,正如成员@Jeeped 所指出的,使用Like 运算符而不是Is(或使用等号"="):

sColumn(n) = sColumn(n) & IIf(sColumn(n) Like vbNullString, "", ",") & oCell.Text

希望这会有所帮助。

【讨论】:

  • 我正在尝试调查它。我仍然有同样的错误
  • 请参考我的扩展答案。最好的问候,
【解决方案2】:

您需要IIF function,而不是 IF。

sColumn(n) = sColumn(n) & _
  IIF(CBool(Len(sColumn(n))), ",", vbNullString) & oCell.Text

此外,您的 sColumn 数组可能是 null/vbnullstring/空字符串。如果 sColumn(n) 中有内容,您只想尝试 Range.AutoFilter Method,如果没有,则不尝试。

' Apply Filter
For n = LBound(sColumn) To UBound(sColumn)
    If sColumn(n) <> vbNullString Then
        oLO.Range.AutoFilter _
        Field:=n, _
        Criteria1:=Split(sColumn(n), ","), _
        Operator:=xlFilterValues
    End If
Next n

您不能将空数组元素(例如 vbNullString)拆分为任何内容,因此您会收到错误 13:类型不匹配。

【讨论】:

  • 感谢以上。我收到以下不匹配错误:oLO.Range.AutoFilter _ Field:=n, _ Criteria1:=Split(sColumn(n), ","), _ Operator:=xlFilterValues
  • 您问题中的其余代码格式错误。你在使用If sColumns(n) &lt;&gt; vbNullString Then 吗?这是不可能的。
  • 很抱歉 "=" ... If sColumns(n) = vbNullString Then
  • 不应该。我正在谈论它在 .AutoFilter 周围的使用位置。如果 不是 vbnullstring,您应该只继续尝试自动过滤器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 2021-06-14
  • 2018-08-12
  • 2016-07-05
  • 1970-01-01
  • 2017-08-21
相关资源
最近更新 更多