VBA - MsgBox 二维数组(矩阵)

VBA - MsgBox a 2D Array (Matrix)

我正在尝试使用 MsgBox 可视化二维矩阵(数组),但我的代码没有给出正确的表示形式。

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

这是我得到的结果:

您已将 wh 互换。

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

这很适合我

Private Sub this()
    Dim this(22, 7) As Integer
    Dim msg$
    For i = LBound(this, 1) To UBound(this, 1)
        For j = LBound(this, 2) To UBound(this, 2)
            msg = msg & this(i, j) & vbTab
        Next j
    Next i
    MsgBox msg
End Sub

编写一个 returns 字符串的函数可能更灵活,这是一种二维连接,它允许您选择项目分隔符(默认为 vbTab)和行分隔符(默认为 vbCrLf)。

您可以 MsgBox 这个字符串 -- 或将其直接写入 window -- 或(选择逗号作为分隔符之一)-- 将其写入 CSV 文件,等:

Function MatrixJoin(M As Variant, Optional delim1 As String = vbTab, Optional delim2 As String = vbCrLf) As String
    Dim i As Long, j As Long
    Dim row As Variant, rows As Variant

    ReDim rows(LBound(M, 1) To UBound(M, 1))
    ReDim row(LBound(M, 2) To UBound(M, 2))

    For i = LBound(M, 1) To UBound(M, 1)
        For j = LBound(M, 2) To UBound(M, 2)
            row(j) = M(i, j)
        Next j
        rows(i) = Join(row, delim1)
    Next i
    MatrixJoin = Join(rows, delim2)
End Function

测试者:

Sub test()
    Dim A As Variant
    A = Range("A1:B3").Value
    MsgBox MatrixJoin(A)
    Debug.Print MatrixJoin(A, ",", ";")
End Sub

输出截图: