VBA 一个find方法的增强函数

'本函数是一个find方法的增强函数,结合FindNext和FindPrevious方法,可以返回一组符合条件的单元格的集合;
'本函数返回一个Collection对象,里面储存了找到的单元格;
'本函数有两个必选参数:
'   1.SearchRange 用来存放需要查找的区域;
'   2.FindWhat用来存放需要查找的值;
'其余参数都是可选参数,与Find方法参数相同;
'无论是否查找到单元格,都会返回一个collection对象;
'我们用Collection.Count=0,来判断,没有找到匹配的单元格;
Option Explicit

Function FindPlus(SearchRange As Range, FindWhat As Variant, _
                  Optional After As Range, _
                  Optional LookIn As Variant = xlFormulas, _
                  Optional LookAt As Variant = xlPart, _
                  Optional SearchOrder As Variant = xlByRows, _
                  Optional SearchDirection As Variant = xlNext, _
                  Optional MatchCase As Variant = False, _
                  Optional MatchByte As Variant = True, _
                  Optional SearchFormat As Variant = False) As Collection

Dim FoundCell As Range '存放找到的单元格区域;
Dim AfterCell As Range '存放查找的起始单元格;
Dim FoundCol As Collection '存放找到单元格区域的集合;
Dim firstAddress As String '存放第一次找到的单元格的地址

Set FoundCol = New Collection 'Collecion类实例化为对象

'下面这个判断语句完成对After参数值的控制
If After Is Nothing Then
Else
  Set AfterCell = After '如果after参数不为空,这用提供的after参数值
End If

'查找第一个符合条件的值
Set FoundCell = SearchRange.Find(what:=FindWhat, After:=AfterCell, _
                              LookIn:=LookIn, _
                              LookAt:=LookAt, _
                              SearchOrder:=SearchOrder, _
                              SearchDirection:=SearchDirection, _
                              MatchCase:=MatchCase, _
                              MatchByte:=MatchByte, _
                              SearchFormat:=SearchFormat)


If Not FoundCell Is Nothing Then
    firstAddress = FoundCell.Address '如果找到第一个值,然后把单元格地址赋值给FirstAddress变量
    
    '下面的循环是在区域里不断查找需要的值,并不断添加到FoundCol集合
    Do
      FoundCol.Add FoundCell '把找到的单元格赋值给FoundCol对象
      
      '根据SearchDirection参数,判断是向上搜索,还是向下搜索
      If SearchDirection = xlNext Then
        Set FoundCell = SearchRange.FindNext(After:=FoundCell)
      Else
        Set FoundCell = SearchRange.FindPrevious(After:=FoundCell)
      End If
    Loop Until (FoundCell Is Nothing) Or (FoundCell.Address = firstAddress) '经典用法,只要找到单元格和第一个找到的单元格地址不一样,就一直循环
End If
Set FindPlus = FoundCol '把集合对象赋值给函数名
End Function

 

转载于:https://www.cnblogs.com/yuzhengdong/p/4199429.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值