【Exel VBA】FIND()

在这里插入图片描述
Find语法:

Range.Find(What,After,LookIn,LookAt,SearchOrder,SearchDirection,MatchCase,MatchByte,SearchFormat)

  1. 参数What,必需指定。代表所要查找的数据,可以为字符串、整数或者其它任何数据类型的数据。对应于“查找与替换”对话框中,“查找内容”文本框中的内容。

  2. 参数After,可选。指定开始查找的位置,即从该位置所在的单元格之后向后或之前向前开始查找(也就是说,开始时不查找该位置所在的单元格,直到Find方法绕回到该单元格时,才对其内容进行查找)。所指定的位置必须是单元格区域中的单个单元格,如果未指定本参数,则将从单元格区域的左上角的单元格之后开始进行查找。

  3. 参数LookIn,可选。指定查找的范围类型,可以为以下常量之一:xlValues、xlFormulas或者xlComments,默认值为xlFormulas。对应于“查找与替换”对话框中,“查找范围”下拉框中的选项。

  4. 参数LookAt,可选。可以为以下常量之一:XlWhole或者xlPart,用来指定所查找的数据是与单元格内容完全匹配还是部分匹配,默认值为xlPart。对应于“查找与替换”对话框中,“单元格匹配”复选框。

  5. 参数SearchOrder,可选。用来确定如何在单元格区域中进行查找,是以行的方式(xlByRows)查找,还是以列的方式(xlByColumns)查找,默认值为xlByRows。

例子1: find one match

Sub One_Find()
    Dim CompId As Range
    
    '在每次执行前,清空目标cell
    Range("C3").ClearContents
    
    ' 在目标range"A:A"中,找符合"B3"的值
    Set CompId = Range("A:A").Find(what:=Range("B3").Value, LookIn:=xlValues, lookat:=xlWhole)

    '如果有找到,则将CompId.Offset(, 4).Value(offset后就是Artical code列)的值填入C3
    If Not CompId Is Nothing Then
        Range("C3").Value = CompId.Offset(, 4).Value
    Else
    MsgBox "Company not found!"
    End If
End Sub

在这里插入图片描述

例子2: find N match

Sub Many_Finds()
    Dim CompId As Range
    ' 用i来循环有几个match
    Dim i As Byte
    ' 记录first match是哪个,决定何时exit loop
    Dim FirstMatch As Variant
    
    ' 同one match, 每次执行后先清空target range
    Range("D3:D6").ClearContents
    i = 3
    Dim Start
    Start = VBA.Timer
    
    Set CompId = Range("A:A").Find(what:=Range("B3").Value, LookIn:=xlValues, lookat:=xlWhole)
    If Not CompId Is Nothing Then
        ' 此时CompId仍是第一个找到的值
        Range("D" & i).Value = CompId.Offset(, 4).Value
        FirstMatch = CompId.Address
        
        Do
            '循环开始,将CompId逐渐+1,FindNext只需要一个argument,就是从哪里开始next
            Set CompId = Range("A:A").FindNext(CompId)
            '如果和Firstmatch一样,则退出
            If CompId.Address = FirstMatch Then Exit Do
            i = i + 1
            Range("D" & i).Value = CompId.Offset(, 4).Value
        Loop
    Else
    MsgBox "Company not found!"
    End If
    Debug.Print Round(Timer - Start, 3)
    
    
    'Application.Speech.Speak "Well Done. " & i - 2 & " matches were found."
    
End Sub

猜你喜欢

转载自blog.csdn.net/Cecilia_W422/article/details/88812650
vba
今日推荐