首页 文章

在excel VBA中查找包含关键字的单元格

提问于
浏览
-2

我想编写一个宏来搜索数据库中的列,并在不同的选项卡中返回包含某个给定关键字的所有单元格 . 换句话说,我想输入“锤子”并获得包含单词hammer的每个单元格的列表,即使单词位于值的中间(例如,“建筑商昨天买了一把锤子”) .

我是VBA的新手,所以我想要一些帮助/输入来使用哪些函数来做到这一点 . 我试过使用AdvancedFilter,但是只查看每个单元格值的开头 . 欢迎所有反馈,谢谢!

1 回答

  • 0

    使用 Range 对象的Autofilter()方法

    Sub main()
        With Worksheets("hammer") '<--| reference searched worksheet (change "hammer" to its actual name)
            With .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)) '<--| reference its column "A" cells from row 1 down to last non empty one (change "A"s to your actual searched column index)
                .AutoFilter Field:=1, Criteria1:="*hammer*" '<--| filter on referenced column to get cell containing "hammer"
                If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Copy Destination:=Worksheets("different tab").Range("A1") '<--| copy any filtered cell into "different tab" worksheet
            End With
            .AutoFilterMode = False '<--| show all rows back
        End With
    End Sub
    

    它假设搜索范围的第一个单元格(在此示例中为"A1")是 Headers 单元格,因此不会搜索"*hammer" .

相关问题