【问题标题】:VBA - MsgBox a 2D Array (Matrix)VBA - MsgBox 一个二维数组(矩阵)
【发布时间】:2017-01-25 13:34:02
【问题描述】:

我正在尝试使用 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

这是我得到的结果:

【问题讨论】:

  • 我认为这是因为您受到msg 长度的限制(所以它正在跳过或其他东西)。您可以尝试将每一行保存在一个字符串中,这样您将拥有一个 Strings 数组,然后循环并在 MsgBox 中显示它们
  • 对于它的价值,我真的很喜欢尝试直观地查看数组输出的想法。
  • @DougCoats 仅在您承诺 +1 的情况下 :)
  • @ShaiRado 我做到了

标签: arrays vba excel msgbox


【解决方案1】:

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

【讨论】:

  • 嗨 CMArg,我相信它们在我的代码中是正确的,否则我会收到“下标超出范围”错误
  • 您正在正确扫描数组​​,但消息框的第一行显示了您的第一个维度的 8 个第一个元素(有 23 个元素),第二行显示了另外 8 个,依此类推。我认为那不是你想要的..
  • 见 Doug 回答:你有 iii 互换(在arr(ii, i))...
  • 这就是问题所在
  • CMArg,你是对的。我更改了代码:第一个循环是 for h 和 for w。我一开始并没有注意这一点,因为我刚刚看到 i 和 ii 在你的回答中互换了。谢谢!
【解决方案2】:

这对我很有效

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

【讨论】:

    【解决方案3】:

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

    您可以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
    

    输出截图:


    【讨论】:

      猜你喜欢
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 2015-03-19
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多