I am unable to figure out how to read in a simple csv file using Excel VBA.
If I want to open and read a csv file, this statement should suffice, as long as the filepath is a valid string?
' Open file and read contents
Open FilePath For Input As #1
FileContent = Input(LOF(1), 1)
Close #1
Then, I want to create a two dimensional array, with rows and columns. I would think this should do the job, but it does not.
' Split file content into rows
RowsArray = Split(FileContent, vbCrLf)
' Split rows into columns
Dim i As Long
For i = LBound(RowsArray) To UBound(RowsArray)
ColumnsArray = Split(RowsArray(i), ",")
Next i
It does not give an error, but the columns array is empty,
The whole function is here:
Public Function ReadCSVFileInToArray(FilePath)
' Define variables
Dim FileContent As String
Dim RowsArray() As String
' Open file and read contents
Open FilePath For Input As #1
FileContent = Input(LOF(1), 1)
Close #1
' Split file content into rows
RowsArray = Split(FileContent, vbCrLf)
' Split rows into columns
Dim i As Long
For i = LBound(RowsArray) To UBound(RowsArray)
ColumnsArray = Split(RowsArray(i), ",")
Next i
ReadCSVFileInToArray = ColumnsArray
End Function
I suspect both RowsArray and ColumnsArray need to be redimensioned, but how do I know the dimensions before splitting them?
It seems like this should be easy, so I'm clearly not understanding something. I can't even find an intelligible explanation on the web.