VBA循环元素在两个相应的数组中

时间:2018-03-23 19:25:11

标签: excel-vba foreach vba excel

我有两个相互对应的数组。我想使用每个数组的第一个元素循环一个函数,然后是每个数组的第二个元素,等等。这是我正在使用的数据。它循环遍历Unit中的元素(For Unit in Unit),但我不确定如何使UM元素循环。这可能吗?或者有更好的方法吗?我对vba缺乏经验,并且非常愿意接受建议!

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

1 个答案:

答案 0 :(得分:2)

使用普通循环,以便您可以引用数组中的位置:

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