1

I am tiring alter a macro by seting a range as my array

This works fine

Sub FindReplaceByArrays()

Dim FindValues As Variant
Dim ReplaceValues As Variant
Dim i As Long

FindValues = Array("Find1", "Find2", "Find3")
ReplaceValues = Array("Replace1", "Replace2", "Replace3")

Sheets("UnPivot").Select
For i = LBound(FindValues) To UBound(FindValues)
     Columns("P:P").Replace FindValues(i), ReplaceValues(i), xlWhole, xlByColumns, False
Next i

End Sub

Tiring to change to the following Sub but get error "Script out of range` and

Columns("P:P").Replace FindValues(i), ReplaceValues(i), xlWhole, xlByColumns, False

is high lighted

Thanks

Sub FindReplaceByArrays2()

Dim FindValues() As Variant
Dim ReplaceValues() As Variant
Dim i As Long

Sheets("UnPivot").Select
FindValues = Range("S2:S30")
ReplaceValues = Range("T2:T30")

For i = LBound(FindValues) To UBound(FindValues)
     Columns("P:P").Replace FindValues(i), ReplaceValues(i), xlWhole, xlByColumns, False
Next i

End Sub
Community
  • 1
  • 1
xyz
  • 2,253
  • 10
  • 46
  • 68

1 Answers1

1

Try this one:

Sub FindReplaceByArrays2()

    Dim FindValues As Variant
    Dim ReplaceValues As Variant
    Dim i As Long

    With Sheets("UnPivot")
        FindValues = .Range("S2:S30").Value
        ReplaceValues = .Range("T2:T30").Value

        For i = LBound(FindValues) To UBound(FindValues)
             .Columns("P:P").Replace FindValues(i, 1), ReplaceValues(i, 1), xlWhole, xlByColumns, False
        Next i
    End With
End Sub

Note, that I'm using

  1. Dim FindValues As Variant instead Dim FindValues() As Variant
  2. FindValues = .Range("S2:S30").Value - with .Value property (you can read about why you should use it here: Why am I having issues assigning a Range to an Array of Variants)
  3. also FindValues = .Range("S2:S30").Value actually creates 2D array, that's why I'm using FindValues(i, 1). The same for ReplaceValues(i, 1)

and also: How to avoid using Select/Active statements:)

Community
  • 1
  • 1
Dmitry Pavliv
  • 35,333
  • 13
  • 79
  • 80