0

I created a matrix within a Sub. I'd like to know, if there any fast way to plot the values of this matrix in a message box?

Here's the code:

Dim A() As Variant

ReDim A(5, 5)
   For i = 1 To 5
       For j = 1 To 5
        A(i, j) = 1
       Next j
 Next i

Trying to plot:

MsgBox A

How can I achieve this easily and fast? Thank you in advance.

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
Übel Yildmar
  • 491
  • 1
  • 9
  • 24
  • What string representation do you want? If you want a formatted "grid" then you would need to implement that yourself. – Alex K. Apr 25 '19 at 14:15

2 Answers2

3

The MsgBox function takes a String argument for its Prompt parameter. A is a 2D Variant array containing 25 Variant/Integer values and 11 Variant/Empty values - the implicit lower bound for implicitly-sized arrays is 0 unless you have Option Base 1 specified; I'd recommend using explicit array bounds e.g. ReDim A(1 To 5, 1 To 5) instead, but that off-by-one error wasn't the question.

VBA doesn't know how you want to represent an array as a string. In .NET the default string representation of an int array looks like this: int[], because the default ToString implementation simply yields the name of the object's data type: other languages might have other default string representations for an array, but the bottom line is, you need to implement that yourself.

Maybe you want it tab-delimited? Or comma-separated?

Easily? Iterate the array and concatenate your string:

Dim s As String
For i = LBound(A, 1) To UBound(A, 1)
    For j = LBound(A, 2) To UBound(A, 2)
        s = s & vbTab & A(i, j)
    Next
    s = s & vbNewLine
Next
MsgBox s

Fast? Use a StringBuilder:

With New StringBuilder
    For i = LBound(A, 1) To UBound(A, 1)
        For j = LBound(A, 2) To UBound(A, 2)
            .Append A(i, j) & vbTab
        Next
        .Append vbNewLine
    Next
    MsgBox .ToString
End With

Fancy? Take a Slice of each i element, use the VBA.Strings.Join function to make each "slice" into a delimited string (specify the separator you need), and append each delimited string to the final string representation.

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
1

Make a string of your array and plot this, try:

Sub tst()
Dim A() As Variant
Dim aa As String

ReDim A(5, 5)
   For i = LBound(A, 1) To UBound(A, 1)
       For j = LBound(A, 2) To UBound(A, 2)
        A(i, j) = 1
        aa = aa & A(i, j) & vbTab
       Next j
        aa = aa & vbCrLf
 Next i
MsgBox aa
End Sub
EvR
  • 3,418
  • 2
  • 13
  • 23