在 VBA 中查找和查找下一个

Find and FindNext in VBA

我正在研究 Excel 宏。从另一个 excel sheet 获取数据时我需要什么,代码应该首先检查是否有任何其他行具有相同的 FundName,如果找到则适用条件。

我只是给出 Excel Sheet 的示例,从中检查 FundId :

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 sheet FindRow 应该有值但是 NextRow returns 没有所以我可以应用我的条件。

如果有人能帮助我,请。

替换为:

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

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