I would attempt this by:
- First splitting the data into rows using vbNewLine.
- Then loop your split array, and split each iteration using your comma delimiter. Leaving you with a jagged array (an array containing arrays).
- Lastly, you now have the dimensions for the two dim array, ReDim and loop over it to add all your data.
For abstraction purposes, I separated this task into three separate functions.
Main function to Call
I made the delimiter optional so it's not restrictive to only commas.
This does not account for escaped characters, you'll have to add that if that is needed.
Private Function TextFileToArray(ByVal FilePath As String, Optional ByVal Delimiter As String = ",") As Variant
'READ THE CONTENTS FROM TEXTFILE
Dim FileContent As String
FileContent = ReadTextFile(FilePath)
'SEPERATE THE ROWS USING vbNewLine
Dim SplitData As Variant
SplitData = Split(FileContent, vbNewLine)
'CREATE A JAGGED ARRAY BY SPLITTING EACH STRING
Dim JaggedArray As Variant
ReDim JaggedArray(LBound(SplitData, 1) To UBound(SplitData, 1))
Dim Index As Long
For Index = LBound(SplitData, 1) To UBound(SplitData, 1)
JaggedArray(Index) = Split(SplitData(Index), Delimiter)
Next Index
'CONVERT JAGGED ARRAY INTO A TWO DIM ARRAY
TextFileToArray = JaggedArrayToTwoDimArray(JaggedArray)
End Function
Read the content of the text file
This could be written in the main function, but it is normally best to try to separate your code into smaller blocks.
Public Function ReadTextFile(ByVal FilePath As String) As String
Dim Fso As Object
Set Fso = CreateObject("Scripting.FileSystemObject")
Dim Ts As Object
Set Ts = Fso.OpenTextFile(FilePath, 1, False)
ReadTextFile = Ts.ReadAll
End Function
Convert Jagged Array into a 2d Array
I've stored the bounds in variables to make it easier to debug and read.
Private Function JaggedArrayToTwoDimArray(ByVal SourceArray As Variant) As Variant
'CAPTURE BOUNDS
Dim LB1 As Long
LB1 = LBound(SourceArray, 1)
Dim UB1 As Long
UB1 = UBound(SourceArray, 1)
Dim LB2 As Long
LB2 = LBound(SourceArray(LB1), 1)
Dim UB2
UB2 = UBound(SourceArray(UB1), 1)
'SET BOUNDS OF RETURN ARRAY
Dim ReturnArray As Variant
ReDim ReturnArray(LB1 To UB1, LB2 To UB2)
'POPULATE TWO DIM ARRAY FROM JAGGED ARRAY
Dim RowIndex As Long
For RowIndex = LB1 To UB1
Dim ColIndex As Long
For ColIndex = LB2 To UB2
ReturnArray(RowIndex, ColIndex) = SourceArray(RowIndex)(ColIndex)
Next ColIndex
Next RowIndex
JaggedArrayToTwoDimArray = ReturnArray
End Function
Please feel free to add error handling and any changes that might be needed.