Home » excel » excel vba – VBA Looping elements in two corresponding arrays

excel vba – VBA Looping elements in two corresponding arrays

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have two arrays which correspond with one another. I’m wanting to loop through a function using the first element of each array, then the second of each, etc. Here’s the data that I’m working with. It cycles through the elements in Unit (For Each element In Unit), but I’m not sure how to make the UM elements cycle as well. Is this possible? Or is there a better way to do this? I’m inexperienced with vba and very open to suggestion!

Dim Unit As Variant
Dim UM As Variant

Unit = Array("BOX", "CASE", "COIL", "EACH", "PACK", "ROLL")
UM = Array("BX", "CS", "CL", "EA", "PK", "RL")

    For Each element In Unit
    Selection.Replace What:=Unit, Replacement:=UM, LookAt:=xlWhole, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Next
How to&Answers:

use a normal loop so you can reference the position in the array:

Dim Unit As Variant
Dim UM As Variant

Unit = Array("BOX", "CASE", "COIL", "EACH", "PACK", "ROLL")
UM = Array("BX", "CS", "CL", "EA", "PK", "RL")
Dim i As Long
    For i = LBound(Unit) To unbound(Unit)
        Selection.Replace What:=Unit(i), Replacement:=UM(i), LookAt:=xlWhole, _
            SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
            ReplaceFormat:=False
    Next