2

I have an array formula in a single cell that outputs some 2D array:

{={"a","b","c"; 1, 2, 3}}

(more complicated of course but that's the last step if I step through)

At the moment I am wrapping this result to return a formatted string as follows:

{="{" & TEXTJOIN(", ",TRUE,{"a","b","c";1,2,3}) &"}"}

Which returns {a, b, c, 1, 2, 3} as a string. This is almost what I want, but the array flattened, there's no way of distinguishing between the 2 rows as the ;-semicolon is missing. I don't care about escaping the letters with "" - my actual use case is all integers

Is there a way to convert a 2D array to some kind of string, preserving row distinctions? Ideally without having to re-reference the array multiple times as I have no room for intermediate arrays, and it would be a little inefficient to recalculate many times.


FWIW my actual formula is

{="{" & TEXTJOIN(", ",TRUE,INDIRECT([@Pt2])*INDIRECT([@Pm2])*INDIRECT([@Pb3])*INDIRECT([@Nt4])*INDIRECT([@Nm5])*INDIRECT([@Nb6])) &"}"}

where the [@...] point to the names of named ranges, each of which is a 6x3 matrix of integers 0 to 2. Thus the formula calculates the elementwise products of 6 different 2D arrays and outputs this as an array. Perhaps you can think of a better way of tackling this, but I've been trying to follow a KISS mentality and this seemed like the most obvious approach to me.

Summary

So what I want is for the array output of the element-wise product

{0,2,0,0,2,1
0,2,2,1,1,0
0,0,0,1,1,0}

to become the string "{0,2,0,0,2,1;0,2,2,1,1,0;0,0,0,1,1,0}" or any other single cell unambiguous 2D array representation. Hope that makes sense:)

Community
  • 1
  • 1
Greedo
  • 4,967
  • 2
  • 30
  • 78

1 Answers1

0

It appears that TEXTJOIN() does not "see" the 2-D structure of the input. However if you enter (or array-enter) this in A1:

={"a","b","c";1,2,3}

and then install this small UDF:

Public Function joyn(rng As Range) As String
    v = rng.Value
    s = ""
    For i = LBound(v, 1) To UBound(v, 1)
        s = s & IIf(s = "", "", ";")
        For j = LBound(v, 2) To UBound(v, 2)
            s = s & v(i, j) & IIf(j = UBound(v, 2), "", ",")
        Next j
    Next i
    joyn = s
End Function

and then in some cell:

=joyn(A1:C2)

we see:

enter image description here

EDIT#1:

If you want to directly wrap an array constant and you are sure it is 2-D, then we can skip the range-to array steps:

Public Function joynAC(v As Variant) As String
    Dim s As String, i As Long, j As Long

    s = ""
    For i = LBound(v, 1) To UBound(v, 1)
        s = s & IIf(s = "", "", ";")
        For j = LBound(v, 2) To UBound(v, 2)
            s = s & v(i, j) & IIf(j = UBound(v, 2), "", ",")
        Next j
    Next i

    joynAC = s
End Function
Gary's Student
  • 95,722
  • 10
  • 59
  • 99