79388114

Date: 2025-01-26 07:05:11
Score: 1
Natty:
Report link

This is a supplement to JvdV's answer:

I must admit it's impressive and enlightening. I guess I'm not the only one who always seeking for a general method to convert a string into 2-Dimensional array without looping and spliting substring populated by row delimiter. I've known that Application.Transpose will convert 1-D array which contains 1-D subarray as element into 2-D array, but I never realized that it can be combined with Index function in such an elegant way!

Now I extend this method to populate any customized size 2-D array in my project, only if I know the column number of that array, take an example:

Assume that I get a Recordset from ADO object by SQL query and retrieve data by .GetString Method (I can't use GetRows method becuz of Null value in the recordset), then divided the string into a N*4 size 2-dimensional array:

Dim adoCnnctn As New ADODB.Connection
Dim strRcrdSt As String
Dim arrRcrdSt As Variant
Dim arrFld1 As Variant, arrFld2 As Variant, arrFld3 As Variant, arrFld4 As Variant

strRcrdSt = adoCnnctn.Execute(strQry).GetString(adClipString, , ",", ",", "N/A")
arrRcrdSt = Split(Left(strRcrdSt, Len(strRcrdSt) - 1), ",")

With Application
    .ReferenceStyle = xlA1
    arrFld1 = Evaluate("=TRANSPOSE((ROW(1:" & (UBound(arrRcrdSt) + 1) / 4 & ")*4)-3)")
    arrFld2 = Evaluate("=TRANSPOSE((ROW(1:" & (UBound(arrRcrdSt) + 1) / 4 & ")*4)-2)")
    arrFld3 = Evaluate("=TRANSPOSE((ROW(1:" & (UBound(arrRcrdSt) + 1) / 4 & ")*4)-1)")
    arrFld4 = Evaluate("=TRANSPOSE((ROW(1:" & (UBound(arrRcrdSt) + 1) / 4 & ")*4)-0)")
    arrRcrdSt = .Transpose(Array( _
                .Index(arrRcrdSt, 1, arrFld1), _
                .Index(arrRcrdSt, 1, arrFld2), _
                .Index(arrRcrdSt, 1, arrFld3), _
                .Index(arrRcrdSt, 1, arrFld4)))
End With

Key points you must pay attetion to:

  1. Watch out the data type of those variables and arrays;
  2. Watch out the subscript of those arrays;
  3. The formula reference style must be xlA1,you can make this mandatory setting by VBA code or set it in the option menu by unchecking R1C1 reference style, otherwise Index function will return "Error 2015"

And thank you! @JvdV

Reasons:
  • Blacklisted phrase (0.5): thank you
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @JvdV
  • Low reputation (1):
Posted by: Meer Molix