continuous loop using Find in Excel VBA

前端 未结 3 1861
深忆病人
深忆病人 2021-01-06 13:34

I have the below code, which I am having trouble with:

Sub getAccNos()

Dim oNameRange As Range
Dim oFindRng As Range

Dim sName As String
Dim sAccNo As Stri         


        
3条回答
  •  旧巷少年郎
    2021-01-06 14:20

    Here is an example. What I would do is count how many occurrences, and then add another variable to increment for each occurrence, and Loop While Not foundCount >= howManyInRange

    Sub FindInRange()
    
    Dim howManyInRange As Long
    Dim foundCount As Long
    Dim oFindRange As Range
    Dim rngSearch As Range
    Dim srchVal As String
    
    srchVal = "Steve"
    Set rngSearch = Range("D:D")
    
    '## First, check to see if the value exists.'
    
    howManyInRange = Application.WorksheetFunction.CountIf(rngSearch, srchVal)
    
    If Not howManyInRange = 0 Then
        Do
            Set oFindRange = rngSearch.Find(what:=srchVal, After:=ActiveCell)
            '## Avoid duplicate and infinite loop:'
            foundCount = foundCount + 1
            oFindRange.Activate
            '## Do your stuff, here.'
    
            Debug.Print oFindRange.Address
    
        Loop While Not foundCount >= howManyInRange
    End If
    
    End Sub
    

提交回复
热议问题