在VBA中查找和查找下一个

时间:2015-01-15 08:53:11

标签: vba excel-vba access-vba excel

我正在使用Excel宏。从另一个Excel工作表中获取数据时我需要的是,代码应首先检查是否存在具有相同FundName的任何其他行,如果找到则适用条件。

我只是提供要检查FundId的Excel Sheet样本:

S.No    Funds
1        A
2        B
3        C
4        D
5        A

代码如下:

Set shtData = wbraw.Sheets(1) ' this line is correct

Set CCell = shtData.Cells.Find("Funds", LookIn:=xlValues, LookAt:=xlWhole).Offset(1, 0)

Set DCell = CCell.End(xlDown)

Dim SearchString as String
SearchString  = "A"  

Set FindRow = shtData.Range(CCell, DCell).Find(What:=SearchString, LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)

Set NextRow = shtData.Range(CCell, DCell).FindNext(After:=FindRow)

代码中的两行不符合我的要求应该是。假设如果SearchString设置为“A”,则FindRow和NextRow都应该具有该值。如果SearchString设置为“B”,那么根据给定的Excel工作表FindRow应该具有值,但NextRow返回Nothing,以便我可以应用我的条件。

请有人帮我。

2 个答案:

答案 0 :(得分:1)

替换它:

Set FindRow = shtData.Range(CCell, DCell).Find(What:=SearchString, LookIn:=xlValues, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)

Set NextRow = shtData.Range(CCell, DCell).FindNext(After:=FindRow)

使用:

If WorksheetFunction.CountIf(CCell.EntireColumn, SearchString) > 1 Then
   'Duplicate found, do something here
Else
   'Unique string, do something here
End If

If Evaluate("COUNTIF(" & CCell.EntireColumn.Address & "," & SearchString & ")") > 1 Then
   'Duplicate found, do something here
Else
   'Unique string, do something here
End If

答案 1 :(得分:1)

Find将使用Range的第一个单元格作为After参数,如果未指定,则搜索在B2之后开始,因此它找到的第一个单元格是B6。 如果订单对您很重要,请使用Find提供的最后一个单元格拨打After

    Dim counter As Integer
    counter = 0

    With shtData.Range(CCell, DCell)
        Set c = .Find(SearchString, LookIn:=xlValues, LookAt:=xlWhole, After:=DCell)
        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                counter = counter + 1
                Debug.Print "The next match #" & counter & " is " & c.Address

                Set c = .FindNext(c)
            Loop While Not c Is Nothing And c.Address <> firstAddress
        End If
    End With