Excel - 按其他列的值过滤列

时间:2016-10-31 08:38:42

标签: excel filtering

找不到这个简单的过滤选项:/ 我需要的是按列C值过滤列A,例如:

标题|头

戴尔|暴民
戴尔|网络
戴尔|德
细胞|网络
细胞|德
Gell |暴民

如果我按B列的值“Mob”过滤A列,我想得到: (列B中包含Mob的所有A列值)

标题|头

戴尔|暴民
戴尔|网络
戴尔|德
Gell |暴民

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

使用VBA:

  • 将过滤器单元的名称定义为filterBy(包含要在col B中搜索的文本的单元格)
  • 将列标题单元格定义为colA
  • 将其粘贴到工作表的VBA代码中

    Private Sub Worksheet_Change(ByVal Target As Range)
      'this checks if FilterBy was changed
      If (Not Intersect(Target, [FilterBy]) Is Nothing) Then Call DoTheFilterThing
    End Sub
    
    Sub DoTheFilterThing()
      Dim row_Offset As Integer
      Dim filters() As String
      ReDim filters(0 To 0)
    
        row_Offset = 1
    
        'Scan the B column and create a list of allowed A values
        'Note: this will populate the list until an empty value in A column is found
        Do While [colA].Offset(row_Offset, 0) <> ""
            If [colA].Offset(row_Offset, 1) = [FilterBy] Then
                filters(UBound(filters)) = [colA].Offset(row_Offset, 0)
                ReDim Preserve filters(0 To UBound(filters) + 1)
            End If
            row_Offset = row_Offset + 1
        Loop
    
        'Now apply the filter
        Range([colA], [colA].Offset(row_Offset - 1, 1)).AutoFilter 1, filters, xlFilterValues, , True
    End Sub