How to print two dimensional array in Immediate window in VBA?
Asked Answered
R

8

24

How to print two dimensional array in Immediate window in VBA ? Does it exist any generic method for doing this ? Some method for ploting one row of array per line in Immediate window could solve this problem, because then only thing to do is to loop this code for each line of array.

Rodi answered 11/1, 2013 at 9:18 Comment(1)
A generic method is to write the whole 2d array to a temporary Worksheet. Surely that's easier than reading lines in the immediate window.Winfrid
T
12

I made a simple loop to do this for anybody's reference:

Sub WriteArrayToImmediateWindow(arrSubA As Variant)

Dim rowString As String
Dim iSubA As Long
Dim jSubA As Long

rowString = ""

Debug.Print
Debug.Print
Debug.Print "The array is: "
For iSubA = 1 To UBound(arrSubA, 1)
    rowString = arrSubA(iSubA, 1)
    For jSubA = 2 To UBound(arrSubA, 2)
        rowString = rowString & "," & arrSubA(iSubA, jSubA)
    Next jSubA
    Debug.Print rowString
Next iSubA

End Sub
Tefillin answered 4/6, 2014 at 12:7 Comment(2)
For debugging purposes during program execution, it's not practical to run a macro. Might even cause problems. For debugging, you'll want a code-free method to spy array-contents. See my code-free method below.Dampen
this assumes index / lower bound of both dimensions of arrsuba is 1. If either is 0, it will skip the 0 element.Chub
D
35

If this is for debugging purposes, it's not convenient to write a macro to view the contents of the array during program execution. Might even cause problems.

For debugging during program execution, you'll want a code-free method you can use across all VB projects, to spy the contents of your array.

  1. In VBA IDE, click View menu > Locals Window
  2. In Local pane, find the array-name. enter image description here
  3. Expand the nodes to find your values. The nodes will differ, depending on the type of array.

In this example, "aLookList" is a variant array. The values under "Value2" come from a range.

enter image description here

enter image description here

Another answer here suggests using the Watch pane. This is similar to my answer, but poster did not explain that you can spy the entire array (all cells) by simply adding the array name to Watch. Then , drill down nodes. The advantage of the Locals Window over the Watch Window, is that with Locals pane, you do not have to manually add the array to the pane, it's already there. So it's a bit less effort.

Dampen answered 12/7, 2016 at 18:10 Comment(1)
the locals disappeared once the code execution finished. By adding a debug point just before the Sub end, I was able to get the required locals.. thanks for the great tip!Sofa
T
12

I made a simple loop to do this for anybody's reference:

Sub WriteArrayToImmediateWindow(arrSubA As Variant)

Dim rowString As String
Dim iSubA As Long
Dim jSubA As Long

rowString = ""

Debug.Print
Debug.Print
Debug.Print "The array is: "
For iSubA = 1 To UBound(arrSubA, 1)
    rowString = arrSubA(iSubA, 1)
    For jSubA = 2 To UBound(arrSubA, 2)
        rowString = rowString & "," & arrSubA(iSubA, jSubA)
    Next jSubA
    Debug.Print rowString
Next iSubA

End Sub
Tefillin answered 4/6, 2014 at 12:7 Comment(2)
For debugging purposes during program execution, it's not practical to run a macro. Might even cause problems. For debugging, you'll want a code-free method to spy array-contents. See my code-free method below.Dampen
this assumes index / lower bound of both dimensions of arrsuba is 1. If either is 0, it will skip the 0 element.Chub
E
10

No, you will either need to;

  • Create & call a function that loops & prints it out to the debug window.
  • If this is for debugging, right click the variable in the IDE & "Add Watch" which will bring up a window that will track changes to the value of the array & display its content when a breakpoint is hit.
Exuviae answered 11/1, 2013 at 12:6 Comment(1)
this is similar to my answer below, but poster did not explain that you can spy the entire array (all cells) by simply adding the array name to Watch. Then , drill down nodes.Dampen
F
1

paste below data in column A(Name ) in column B (Age)

Name    Age
A   10
B   20
C   30
D   40
E   50
F   60
G   70

and run the below code

Sub Array_Demo()

Dim arr() As String
Dim i As Integer, j As Integer

' fill the array with strings

Last = Range("A" & Rows.Count).End(xlUp).Row
ReDim arr(Last, 1)

For i = 0 To Last - 1

    arr(i, 0) = Cells(i + 1, 1).Value
    arr(i, 1) = Cells(i + 1, 2).Value


Next

' only one loop to display its contents !!!
Dim v As Variant

For Each v In arr

    Debug.Print v

Next


End Sub

You can see the below output in Immediate window

Name
A
B
C
D
E
F
G

Age
10
20
30
40
50
60
70
Fante answered 27/12, 2016 at 10:23 Comment(0)
A
1

Try This

You can also type code1: code2 instead of code1 _
This is only for displaying
If arr is defined as array( array(,),array(,)...)
and Then
You shoud For c = Lbound(arr(r),1) to ubound(arr(r),1)
Debug.Print arr(r)(c)
Because first is 2d Array and the last is 1nd Array.
I
'Define 2d array
arr = [ {"A",1; "B",2; "C",3 } ]: _
For r = LBound(arr, 1) To UBound(arr, 1): _
        For c = LBound(arr, 2) To UBound(arr, 2): _
            Debug.Print arr(r, c): _
       Next c: _
Next
Ambulance answered 10/1, 2018 at 5:15 Comment(1)
for clarity edits to answer: (1) a semicolon after between the debug.print and the : stop it doing a newline between columns (2) an extra print between next c and next r to force a newline between rows (3) changed to next r to help the nervous (4) the debug. is not needed in the immediate window and in all its single line glory this produces For r = LBound(arr, 1) To UBound(arr, 1) : For c = LBound(arr, 2) To UBound(arr, 2) : Print arr(r, c) ; : Next c : Print : Next r (and i must try to remember the : _ trick to aid readability)Tarragona
S
1

This method outputs an array to the immediate debug window. It auto adjusts the width of the columns and outlines columns to the right, making it easier to compare numbers in the same column.

Public Sub Array2DToImmediate(ByVal arr As Variant, _
                                Optional ByVal spaces_between_columns As Long = 2, _
                                Optional ByVal NrOfColsToOutlineLeft As Long = 2)
'Prints a 2D-array of values to a table (with same sized column widhts) in the immmediate window

'Each character in the Immediate window of VB Editor (CTRL+G to show) has the same pixel width,
'thus giving the option to output a proper looking 2D-array (a table with variable string lenghts).
Dim i As Long, j As Long
Dim arrMaxLenPerCol() As Long
Dim str As String
Dim maxLength As Long: maxLength = 198 * 1021& 'capacity of Immediate window is about 200 lines of 1021 characters per line.

'determine max stringlength per column
ReDim arrMaxLenPerCol(UBound(arr, 1))
For i = LBound(arr, 1) To UBound(arr, 1)
    For j = LBound(arr, 2) To UBound(arr, 2)
        arrMaxLenPerCol(i) = IIf(Len(arr(i, j)) > arrMaxLenPerCol(i), Len(arr(i, j)), arrMaxLenPerCol(i))
    Next j
Next i

'build table
For j = LBound(arr, 2) To UBound(arr, 2)
    For i = LBound(arr, 1) To UBound(arr, 1)
        'outline left --> value & spaces & column_spaces
        If i < NrOfColsToOutlineLeft Then
            On Error Resume Next
            str = str & arr(i, j) & space$((arrMaxLenPerCol(i) - Len(arr(i, j)) + spaces_between_columns) * 1)
        
        'last column to outline left --> value & spaces
        ElseIf i = NrOfColsToOutlineLeft Then
            On Error Resume Next
            str = str & arr(i, j) & space$((arrMaxLenPerCol(i) - Len(arr(i, j))) * 1)
                    
        'outline right --> spaces & column_spaces & value
        Else 'i > NrOfColsToOutlineLeft Then
            On Error Resume Next
            str = str & space$((arrMaxLenPerCol(i) - Len(arr(i, j)) + spaces_between_columns) * 1) & arr(i, j)
        End If
    Next i
    str = str & vbNewLine
    If Len(str) > maxLength Then GoTo theEnd
Next j

theEnd:
'capacity of Immediate window is about 200 lines of 1021 characters per line.
If Len(str) > maxLength Then str = Left(str, maxLength) & vbNewLine & " - Table to large for Immediate window"
Debug.Print str
End Sub

Sub for for example output:

Sub testArray2DToImmediate()
Dim ar() As Variant
ReDim ar(1 To 5, 1 To 4)

ar(1, 1) = "ID": ar(2, 1) = "Name": ar(3, 1) = "Values1": ar(4, 1) = "Values2": ar(5, 1) = "Values3"
ar(1, 2) = 1: ar(2, 2) = "Example where only": ar(3, 2) = FormatNumber(123 * 123#, 2): ar(4, 2) = 89: ar(5, 2) = "Wow"
ar(1, 3) = 2: ar(2, 3) = "first 2 columns are": ar(3, 3) = FormatNumber(234 * 234#, 2): ar(4, 3) = 456789: ar(5, 3) = "Nice"
ar(1, 4) = 3: ar(2, 4) = "outlined Left": ar(3, 4) = FormatNumber(567 * 567#, 2): ar(4, 4) = 123456789: ar(5, 4) = "Table":

Array2DToImmediate ar
End Sub

Example output:

ID  Name                    Values1    Values2  Values3
1   Example where only    15.129,00         89      Wow
2   first 2 columns are   54.756,00     456789     Nice
3   outlined Left        321.489,00  123456789    Table
Saliva answered 11/6, 2021 at 9:47 Comment(0)
L
0

Following procedure uses a function to print array in immediate window. The function converts the array to string row by row.

Sub test()
'declare the 2D array
   Dim intA(0 To 2, 0 To 3) As Integer
'populate the array
   intA(0, 0) = 45:   intA(0, 1) = 50:   intA(0, 2) = 55:   intA(0, 3) = 60
   intA(1, 0) = 65:   intA(1, 1) = 70:   intA(1, 2) = 75:   intA(1, 3) = 80
   intA(2, 0) = 85:   intA(2, 1) = 90:   intA(2, 2) = 95:   intA(2, 3) = 100
Debug.Print Print2DArrayToImmediate(intA)

' <<<<<<<<<<    Or  >>>>>>>>>>
Dim myarr()
myarr = Range("A1:C5").Value
Debug.Print Print2DArrayToImmediate(myarr)

End Sub

Function Print2DArrayToImmediate(arr)
Dim arrStr As String, x As Long, y As Long
arrStr = ""

For i = LBound(arr, 1) To UBound(arr, 1)
    If LBound(arr, 1) = 0 Then i = i + 1
    arrStr = arrStr & vbCrLf
    arrStr = arrStr & Join(Application.Index(arr, i, 0), vbTab & vbTab)
Next i

Print2DArrayToImmediate = arrStr
End Function

enter image description here

Lutestring answered 3/7, 2021 at 6:45 Comment(0)
R
-1

I wrote my own function for this. print_r() for VBA. It can evaluate Arrays, Dictionaries, Collection, MatchCollection etc.. The whole also nested. In addition, the data types are given and special characters are displayed in strings as Unicode.

http://wiki.yaslaw.info/doku.php/vba/functions/print_r/index

print_r(array(1,2,3,array("A","B")))
<Variant()>  (
    [0] => <Integer> 1
    [1] => <Integer> 2
    [2] => <Integer> 3
    [3] => <Variant()>  (
        [0] => <String> 'A'
        [1] => <String> 'B'
    )
)

print_r([{1,2;3,4}])
<Variant()>  (
    [1.1] => <Double> 1
    [1.2] => <Double> 2
    [2.1] => <Double> 3
    [2.2] => <Double> 4
)
Robey answered 8/11, 2018 at 14:11 Comment(2)
Please read: How not to be a spammerJollanta
test array is a nested array not a 2d arrayGluttonize

© 2022 - 2024 — McMap. All rights reserved.