office交流網--QQ交流群號

Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

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

Excel vba 選中符閤條件的單元格數據

2021-01-25 08:00:00
tmtony8
原創
7132

在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

    分享