两个阵列之间的交替输出

时间:2015-07-09 23:04:32

标签: arrays vba for-loop

信不信由我搜索过google,Stack,MSDN并查看了无数代码示例,这些代码提供了各种数组的示例。我可以使用简单的数组来处理For ... Next循环;如下所示,但无论我如何构造下面的代码,我都无法得到输出反映,以便每个代码在每个数组之间来回切换,一次一个变量。任何想法。

我是否必须在数组中创建一个数组?锯齿状阵列?我已经研究过多维数组,看起来它们可能是正确的方法。但是,我不确定。

好的,现在downvote和diss away! -_-

Sub Array 123()
Dim myarray As Variant
Dim myarray2 As Variant

'Let's assume ranges a1, a2 and a3 contain values 1, 2 and 3 and that
'ranges a4, a5 and a6 contain values 4, 5 and 6

myarray = ThisWorkbook.Worksheets("sheet6").Range("a1:a3").Value
myarray2 = ThisWorkbook.Worksheets("sheet6").Range("a4:a6").Value

For i = 1 To UBound(myarray)
MsgBox myarray(i, 1)

Next i

For j = 1 To UBound(myarray2)
MsgBox myarray2(j, 1)

Next j
End Sub


'the out put will be:

[ 1 2 3 4 5 6 ] 

'how would one arrange the structure of the code above so that the output is:

[ 1 4 2 5 3 6 ]

1 个答案:

答案 0 :(得分:2)

移动它:

MsgBox myarray2(j, 1)

进入第一个for循环并删除第二个for循环。

编辑:哦,将j更改为i,稍微调换一下就可以让事情变得更轻松。

以下是您修改后的代码:

Sub Array_123()
Dim myarray As Variant, myarray2 As Variant

'Let's assume ranges a1, a2 and a3 contain values 1, 2 and 3 and that
'ranges a4, a5 and a6 contain values 4, 5 and 6

'We use transpose to make this a 1D array, much easier to play with than a 2D one.
myarray = Application.Transpose(ThisWorkbook.Worksheets("sheet6").Range("a1:a3").Value)
myarray2 = Application.Transpose(ThisWorkbook.Worksheets("sheet6").Range("a4:a6").Value)

For i = 1 To UBound(myarray)
    MsgBox myarray(i)
    MsgBox myarray2(i)
Next i
End Sub