2017-01-25 268 views
2

我想使用MsgBox可视化二维矩阵(数组),但我有的代码并没有给我正确的表示。VBA - 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 

这是结果我得到:

enter image description here

+0

我想这是因为你被'msg'长度的限制(所以它的跳跃或东西)。你可以尝试将每一行保存在一个字符串中,这样你就可以得到一个'String'数组,然后在一个'MsgBox'中循环并显示它们。 –

+0

对于我真的很喜欢试图看到以可视方式输出数组。 –

+0

@DougCoats只有你答应+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 
+0

嗨CMArg,我相信他们在我的代码是正确的,否则我得到“下标超出范围”错误 – Trenera

+1

你正在扫描数组正确,但消息框的第一行显示了第一个维度(包含23个元素)的8个第一个元素,第二个元素包含了8个元素,等等。并且我认为那不是你想要的。 – CMArg

+1

看到Doug答案:你有'ii'和'i'互换(在'arr(ii,i)')... – CMArg

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

0

这可能是更灵活地编写一个函数返回一个字符串,排序的2维连接,它允许你选择项目分隔符(默认为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