Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

excel - VBA pasting 3 dimensional array into sheet

I have a 3 dimensional array (5 x 5 x 3) and I need to post (5 x 5 x 1) to Sheet1, (5 x 5 x 2) to Sheet2, (5 x 5 x 3) to Sheet3. Because I am building this 3 dimensional array inside 3 nested for loops, I cannot use a for loop to access the (5 x 5) part of the loop. Is there any identifier that tells excel to index all elements of an array, such as in MatLab by using (1:end, 1:end, 1)? Basic code is below:

Sub practice_2()

Dim arr(1 To 5, 1 To 5, 1 To 3)
Dim a As Integer
Dim x As Integer
Dim y As Integer

    For a = 1 To 3
        For x = 1 To 5
            For y = 1 To 5
                arr(x, y, a) = x * y
            Next
        Next

        Sheets(a).Select
        'Following line is where I want to access the (5 x 5 x 1) array
        Range(Cells(1, 1), Cells(5, 5)) = arr
    Next
End Sub 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's not much you can do directly with a 3-D array in Excel. However, VBA Variants are pretty flexible. You could get what you want by using a 1-D array that contains 2-D arrays instead of a 3-D array:

Dim arr(1 To 3)

Dim a As Integer
Dim x As Integer
Dim y As Integer

For a = 1 To 3
    ReDim inner(1 To 5, 1 To 5)

    'don't worry...makes a copy
    arr(a) = inner

    For x = 1 To 5
        For y = 1 To 5
            arr(a)(x, y) = a * x * y
        Next
    Next

    Sheets(a).Select

    Range(Cells(1, 1), Cells(5, 5)) = arr(a)
Next

(In answer to your specific question about array syntax, the answer is "no".)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...