Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA - Split CSV file in multidimensional array

I have a .csv which is in the following format:

[TestHeader]FIELDS,"LANGUAGE","LC_NUMERIC","CELLNAME","TESTTYPE","REPORTER","TITLE","STARTDATE","STARTTIME","ENDDATE","ENDTIME"DATATYPE,"Text(80)","Text(80)","Text(64)","Text(80)","Text(80)","Text(80)","Text(12)","Text(20)","Text(12)","Text(20)"

I would like to put this data in a multidimensional array that would mimic as if it was in a sheet. Where the cells are empty it would be empty in the array as well. enter image description here

I am trying to use the following but it only puts the data in a 1D array which is not suitable for what I need.

Dim Delimiter As String
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
Dim LineArray() As String
Dim DataArray() As String

'Inputs
  Delimiter = ","
  FilePath = emiFilePath
  
'Open the text file in a Read State
  TextFile = FreeFile
  Open FilePath For Input As TextFile
  
'Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

'Close Text File
  Close TextFile
  
'Separate Out lines of data
  LineArray() = Split(FileContent, Delimiter, -1, vbTextCompare)

'Read Data into an Array Variable
      'Re-Adjust Array boundaries
        ReDim Preserve DataArray(UBound(LineArray))
'
      'Load line of data into Array variable
        For y = LBound(LineArray) To UBound(LineArray)
          DataArray(y) = Replace(LineArray(y), Chr(34), vbNullString)
        Next y
like image 428
peetman Avatar asked Jan 21 '26 08:01

peetman


1 Answers

With the help of @Ralph and @VincentG

Dim Delimiter As String
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
Dim LineArray() As String
Dim DataArray() As Variant

'Inputs
  Delimiter = ","
  FilePath = emiFilePath

'Open the text file in a Read State
  TextFile = FreeFile
  Open FilePath For Input As TextFile

'Store file content inside a variable
  FileContent = Input(LOF(TextFile), TextFile)

'Close Text File
  Close TextFile

'Separate Out lines of data
  LineArray() = Split(FileContent, vbLf, -1, vbTextCompare)

'Read Data into an Array Variable
      'Re-Adjust Array boundaries
        ReDim Preserve DataArray(UBound(LineArray))
'
      'Load line of data into Array, separate by commas and remove unwanted blank strings
        For y = LBound(LineArray) To UBound(LineArray)
          DataArray(y) = Split(Replace(LineArray(y), Chr(34), vbNullString), Delimiter)
        Next y
like image 146
peetman Avatar answered Jan 22 '26 21:01

peetman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!