Search code examples
arraysvbaexcelmsgbox

VBA - MsgBox a 2D Array (Matrix)


I am trying to visualize a 2D Matrix (Array) using a MsgBox, but the code I have doesn't give me the correct representation.

Sub test()

Dim M(22, 7) As Double
TwoD_Array_Matrix_In_MSGBOX (M)

End Sub
'_________________________________________________________________________

Public Function TwoD_Array_Matrix_In_MSGBOX(arr As Variant)

h = UBound(arr, 1)
w = UBound(arr, 2)
'MsgBox ("h = " & CStr(h + 1) & vbCrLf & "w = " & CStr(w + 1)) ' to check if the width and hight of the Matrix are correct
Dim msg As String

For i = 0 To w
    For ii = 0 To h
        msg = msg & arr(ii, i) & vbTab
    Next ii
    msg = msg & vbCrLf
Next i

MsgBox msg

End Function

This is the result I get:

enter image description here


Solution

  • You have w and h interchanged.

    Dim msg As String
    
    For i = 0 To h
        For ii = 0 To w
            msg = msg & arr(i, ii) & vbTab
        Next ii
        msg = msg & vbCrLf
    Next i
    
    MsgBox msg