Home » excel » arrays – Excel VBA – How to copy a 2D matrix content from a 3D matrix with a single command?

arrays – Excel VBA – How to copy a 2D matrix content from a 3D matrix with a single command?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a 3D matrix, which contains something I would like to write in a range of cells using the command:

Worksheet.Range(Worksheet.Cells(RowStart, ColumnStart), Worksheet.Cells(RowEnd, ColumnEnd)).Value = MyData

The problem is that MyData‘s data is actually described by index = 2 of the first dimension of a 3D matrix.

Since I don’t see the possibility to use Application.WorksheetFunction.Index here, I would like to copy the content of the whole specific index of the 3D matrix inside a 2D one.

Is this possible without having to resort to a For loop (or writing a subroutine that does it)?

How to&Answers:

I’ve made that custom Sub a while ago to display part of a 3D array :

Public Sub Print2D_of_3D_Array(ByVal ArrayT As Variant, _
                ByVal FixedDim As Integer, _
                ByVal FixedDimValue As Double, _
                ByRef Sheet_to_PrintOn As Worksheet, _
                Optional ByVal DeleteSheet As Boolean = False)


If DeleteSheet Then Set Sheet_to_PrintOn = DeleteAndAddSheet(Sheet_to_PrintOn)

Select Case FixedDim
    Case Is = 1
        For i = LBound(ArrayT, 2) To UBound(ArrayT, 2)
            For j = LBound(ArrayT, 3) To UBound(ArrayT, 3)
              Sheet_to_PrintOn.Cells(i + 1, j + 1) = ArrayT(FixedDimValue, i, j)
            Next j
        Next i
    Case Is = 2
        For i = LBound(ArrayT, 1) To UBound(ArrayT, 1)
            For j = LBound(ArrayT, 3) To UBound(ArrayT, 3)
              Sheet_to_PrintOn.Cells(i + 1, j + 1) = ArrayT(i, FixedDimValue, j)
            Next j
        Next i
    Case Is = 3
        For i = LBound(ArrayT, 1) To UBound(ArrayT, 1)
            For j = LBound(ArrayT, 2) To UBound(ArrayT, 2)
              Sheet_to_PrintOn.Cells(i + 1, j + 1) = ArrayT(i, j, FixedDimValue)
            Next j
        Next i
    Case Else
        MsgBox "error"
End Select

End Sub

So, you’d have to use it like this :

Call Print2D_of_3D_Array(MyArray, 1, 2, WorksheetVariable, False)