Excel按首字母筛选一列以获取2个以上的值

时间:2018-08-23 14:44:44

标签: vba excel-vba excel-formula

我在vba刚起步,现在正在与一个宏进行斗争,该宏将按首个确切字母过滤Column(例如,我有Column N-“ City”,因此我必须拥有所有条目,以“ Vancouver”,“ Vancouver。BC”,“ Vancouver Canada”开头-因此,我想按首字母VANCOU对该列进行排序,以确保我不会错过任何信息。

下面的代码对于3个值根本不起作用–可能我选择了错误的方式。请您指教–在这种情况下哪个函数或运算符可以工作?我找到的全部-工作2个值(在那种情况下,我可以在列表“ begins with”中使用)。我有5-6个值,它们可能会有所不同(我不知道下次我会使用哪种格式的城市名称)。

谢谢!

Dim rng01 As Range
Set rng01 = [A1:Z5048]
    rng01.Parent.AutoFilterMode = False
    rng01.Columns(14).AutoFilter Field:=1, Criteria1:=Array("Vancou*", "Brampt*", "Halifa*"), Operator:= _
        xlFilterValues

img1

已更新: 这是经过修改的代码,该代码不起作用

Option Explicit
Sub AutoFilterWorkaround()

Dim sht As Worksheet
Dim filterarr As Variant, tofindarr As Variant
Dim lastrow As Long, i As Long, j As Long, k As Long

Set sht = ThisWorkbook.Worksheets("Sheet1")
lastrow = sht.Cells(sht.Rows.Count, "N").End(xlUp).Row

'List the parts of the words you need to find here
tofindarr = Array("Vancou", "Brampt", "Halifa")

ReDim filterarr(0 To 0)
j = 0

For k = 0 To UBound(tofindarr)

    For i = 2 To lastrow
        If InStr(sht.Cells(i, 14).Value, tofindarr(k)) > 0 Then
            filterarr(j) = sht.Cells(i, 14).Value
            j = j + 1
            ReDim Preserve filterarr(0 To j)
        End If
    Next i

Next k

'Filter on array
sht.Range("$N$1:$N$" & lastrow).AutoFilter Field:=14, Criteria1:=Array(filterarr), Operator:=xlFilterValues

End Sub

1 个答案:

答案 0 :(得分:3)

好的,所以我改写了变通方法-基本上,我们避免使用通配符,方法是找到每个单独的区分大小写,将其装入数组,然后最后对整个数组进行过滤。

此示例适用于列A-只需将lastrow中的A更改为N,并将最后一行中的As更改为Ns。同时在Set sht行上指定工作表名称。同样,您需要将第N列的Field:=1更改为Field:=14

Option Explicit
Sub AutoFilterWorkaround()

Dim sht As Worksheet
Dim filterarr As Variant, tofindarr As Variant
Dim lastrow As Long, i As Long, j As Long, k As Long

Set sht = ThisWorkbook.Worksheets("Sheet1")
lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

'List the parts of the words you need to find here
tofindarr = Array("Vancou", "Brampt", "Halifa")

ReDim filterarr(0 To 0)
j = 0

For k = 0 To UBound(tofindarr)

    For i = 2 To lastrow
        If InStr(sht.Cells(i, 1).Value, tofindarr(k)) > 0 Then
            filterarr(j) = sht.Cells(i, 1).Value
            j = j + 1
            ReDim Preserve filterarr(0 To j)
        End If
    Next i

Next k

'Filter on array
sht.Range("$A$1:$A$" & lastrow).AutoFilter Field:=1, Criteria1:=Array(filterarr), Operator:=xlFilterValues

End Sub

img1