office交流网--QQ交流群号

Access培训群:792054000         Excel免费交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

Excel vba 选中符合条件的单元格数据

2021-01-25 08:00:00
tmtony8
原创
7110

在Excel工作表中查找符合条件的数据。我们可以用条件格式。设置相关的条件,可以以不同格式突出显示符合条件的数据

也可以用vba代码,判断范围内数据是否符合条件,符合条件的被选中。

如图,选中所有超过60的单元格。


详细代码如下:

Sub SelectByValue()
    Dim Cell As Object
    Dim FoundCells As Range
    Dim WorkRange As Range
    
    If TypeName(Selection) <> "Range" Then Exit Sub
    
    If Selection.CountLarge = 1 Then
        Set WorkRange = ActiveSheet.UsedRange
    Else
       Set WorkRange = Application.Intersect(Selection, ActiveSheet.UsedRange)
    End If
    
    On Error Resume Next
    Set WorkRange = WorkRange.SpecialCells(xlConstants, xlNumbers)
    If WorkRange Is Nothing Then Exit Sub
    On Error GoTo 0
    
    For Each Cell In WorkRange
        If Cell.Value >60   Then
            If FoundCells Is Nothing Then
                Set FoundCells = Cell
            Else
                Set FoundCells = Application.Union(FoundCells, Cell)
            End If
        End If
    Next Cell


    If FoundCells Is Nothing Then
        MsgBox "没有记录"
    Else
        FoundCells.Select
        MsgBox "找到 " & FoundCells.Count & " 个数据"
    End If
End Sub

    分享