Nice question. You need to Join
the array into a string:
Sub Filtering()
Dim arr As Variant: arr = Array("Hello", "World", "Wide", "Web")
With Application
Dim MX_LEN As Long: MX_LEN = .Evaluate("MAX(LEN({""" & Join(arr, """,""") & """}))")
End With
End Sub
To elaborate a bit more on why this works:
.Evaluate
needs to be fed a string in the form of a valid formula. Therefor we need to think how we would write this out in an excel sheet. OP mentioned that MX_LEN = EVALUATE("MAX(LEN(" & Rng.Address & "))")
worked. Very logical because on a worksheet that would read (lets assume rng to be A1:A5
):
=MAX(LEN(A1:A5))
Now, because Evaluate
will recognize that we meant to enter this as an array formula, it will return the correct value.
OP said he want's to feed to function an array. Therefor we can reverse the logic and think how a function on the sheet would look like:
=MAX(LEN({"Hello", "World", "Wide", "Web"}))
Now we just need to build that string using Join
and not forget the curly paranthesis. To check if we build it up correctly one can check with Debug.Print "MAX(LEN({""" & Join(arr, """,""") & """}))"
If we want to mimic this, but instead for the first dimension of a two-dimensional array we can apply the following:
With Application
MX_LEN = .Evaluate("MAX(LEN({""" & Join(.Transpose(.Index(arr, 0, 1)), """,""") & """}))")
End With
One catch, just as with a lot more occasions, your string cannot exceed more than 255 characters. Otherwise Evaluate
will return an error (as per documentation)
That means .Evaluate
cannot be used on large strings, making a loop over the array the most effective go-to strategy.
However, if you really don't want to loop you can populate a cell with a formula instead, and read the cell's resulting value2
:
With Application
Sheet1.Range("A1").Formula = "=MAX(LEN({""" & Join(.Transpose(.Index(arr, 0, 1)), """,""") & """}))"
End With
Now you can read this through:
MX_LEN = Sheet1.Range("A1").Value2