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