Forum Discussion

mlondonop's avatar
mlondonop
Copper Contributor
Jul 21, 2022
Solved

Find in excel VBA

I am trying to use the find function in excel VBA inside of a loop. Frist pass would make the "what" in this find function as the value in file A cell B4, and then look for this value in file B and t...
  • HansVogelaar's avatar
    Jul 22, 2022

    mlondonop 

    Your description is not very specific, so my reply is vague too.

    By "file", do you mean a worksheet in the active workbook?

    Sub ReplaceLoop()
        ' Column to search on sheet B
        Const col = "D"
        ' Offset to use
        Const offs = 5
        ' Replacement text
        Const repl = "Replacement Text"
        Dim wsA As Worksheet
        Dim wsB As Worksheet
        Dim r As Long
        Dim m As Long
        Dim s As String
        Dim rng As Range
        Dim adr As String
        Application.ScreenUpdating = False
        ' Use the real names of the worksheets
        Set wsA = Worksheets("A")
        Set wsB = Worksheets("B")
        m = wsA.Range("B" & wsA.Rows.Count).End(xlUp).Row
        For r = 4 To m Step 8
            s = wsA.Range("B" & r).Value
            Set rng = wsB.Columns(col).Find(What:=s, LookAt:=xlWhole)
            If Not rng Is Nothing Then
                adr = rng.Address
                Do
                    rng.Offset(0, offs).Value = repl
                    Set rng = wsB.Columns(col).Find(What:=s, After:=rng, LookAt:=xlWhole)
                    If rng Is Nothing Then Exit Do
                Loop Until rng.Address = adr
            End If
        Next r
        Application.ScreenUpdating = True
    End Sub

Resources