VBA - MsgBox是一个2D数组(矩阵)

时间:2017-01-25 13:34:02

标签: arrays vba excel-vba msgbox excel

我正在尝试使用MsgBox可视化2D矩阵(数组),但我所拥有的代码并没有给我正确的表示。

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

这是我得到的结果:

enter image description here

3 个答案:

答案 0 :(得分:3)

这对我来说很完美

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

enter image description here

答案 1 :(得分:2)

您已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

答案 2 :(得分:0)

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

您可以MsgBox此字符串 - 或将其写入即时窗口 - 或(使用逗号选择作为分隔符之一) - 将其写入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

输出屏幕截图:

enter image description here

enter image description here

相关问题