1. 程式人生 > >Excel-VBA入門(7): 條件定位/分解字串

Excel-VBA入門(7): 條件定位/分解字串

1. 按條件定位

例項1: 定位score大於80的單元格

      

思路1: range.specialcells 定位區域的數值, 然後又for each ...next 進行遍歷, 對區域中的每一個單元格與80進行比較, 大於80則用union函式進行合併進來為range物件. 最後用range.select 進行選中.

Sub test()
    Dim r As Range, r1 As Range, cell As Range, i As Long
    On Error Resume Next ' 程式報錯就進入下一步
    Set
r = ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants, xlNumbers) If Err = 1004 Then MsgBox "當前沒有數值", 64, "提示": Exit Sub For Each cell In r If cell.Value > 80 Then i = i + 1 If i = 1 Then Set r1 = cell Else Set r1 = Union(r1, cell) End If Next
cell If i > 0 Then '存在符合條件的單元格 r1.Select Application.StatusBar = "找到了" & i & "個大於80的單元格" End If End Sub

 range.specialcells()  可以定位單元格: 錯誤值, 邏輯值, 文字, 空值, 圖形物件等

注意如果定位不到單元格就會報錯, 1004 程式碼, 因此需要對報錯進行處理 on error resume next

例項2: 選出不及格學科三門以上的學生姓名

思路: 將姓名, 成績所在的區域賦值給陣列變數arr, 兩次迴圈遍歷陣列的每行每列.

Sub test()
    Dim arr, r As Range, cnt As Integer, i As Integer, j As Integer
    Debug.Print Rows.Count '1048576
    Debug.Print Cells(Rows.Count, "A").End(xlUp).Row '9
    arr = Range("B2:G" & Cells(Rows.Count, "A").End(xlUp).Row).Value ' 成績區賦值
    Debug.Print UBound(arr) & ";" & UBound(arr, 2) '8;6, 8行, 6列
    
    For i = 1 To UBound(arr) ' 遍歷每一行
    cnt = 0
    For j = 1 To UBound(arr, 2) '每一列
        If arr(i, j) < 60 Then
        cnt = cnt + 1
        If cnt = 3 Then
            If r Is Nothing Then ' r還沒有初始化
                Set r = Cells(i + 1, 1) ' 姓名
            Else
                Set r = Union(r, Cells(i + 1, 1))
            End If
            Exit For '結束迴圈
        End If
        End If
    Next j
    Next i
If Not r Is Nothing Then r.Select
End Sub

注意: 如果沒有 r 是nothing 的判斷, 直接用union會報錯! 

Cells(Rows.Count, "A").End(xlUp).Row 表示A列最後一個非空行的行號! 

例項3: 將字串的文字數字進行分解

Sub divide_str(r As Range)
    Dim cell As Range, i As Integer, str As String, hz As String, sz As String, _
    zm As String
    For Each cell In r
    If Len(cell) > 0 Then ' 非空單元格
        For i = 1 To Len(cell.Text) ' 遍歷單元格的每一個字元
        str = Mid$(cell.Text, i, 1) ' 提取字元
        ' ASCII碼小於0 就是漢子
        If Asc(str) < 0 Then hz = ha & str
        If str Like "[a-z,A-Z]" Then zm = zm & str
        If str Like "[0-9.]" Then sz = sz & str
        Next i
    End If
    ' 在選取右邊的三個單元格寫上 漢子, 數字, 字母
        cell.Offset(0, 1) = hz
        cell.Offset(0, 2) = sz
        cell.Offset(0, 3) = zm
        hz = "": sz = "": zm = ""
    Next cell
End Sub
Sub test()
    Call divide_str(Selection) '用之前先自己手動選擇一下區域
End Sub