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列最后一个非空行的行号! 

扫描二维码关注公众号,回复: 4517965 查看本文章

实例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

猜你喜欢

转载自www.cnblogs.com/xuying-fall/p/10121595.html