Tested in Excel 365 (16.8730.2046) 64-bit. All links open in new tab.
- Public Sub CSVToRecordset()
- '===================================================================================
- ' Created by: Sanda Vladescu
- ' Updated on:
- ' Purpose: create a recordset from a csv file
- ' References: Microsoft ActiveX Data object
- ' Usage example:
- '
- '===================================================================================
- ' needs reference to Microsoft ActiveX Data object...
- Dim folderPath As String, FileName As String, FilePath As String
- Dim cn As ADODB.Connection
- Dim rs As ADODB.Recordset
- Dim strSQL, i
- FilePath = PickFileOrFolder(1)
- folderPath = Left(FilePath, InStrRev(FilePath, "\") - 1)
- FileName = Right(FilePath, Len(FilePath) - Len(folderPath) - 1)
- Set rs = ReadCSV(";", folderPath, FileName)
- For i = 0 To rs.Fields.Count - 1
- Debug.Print rs.Fields(i).Name & ":", rs.Fields(i).Value
- Next i
- ' do things with the recordset
- Set rs = Nothing
- End Sub
- '
- Public Function ReadCSV(Delim As String, FilePath As String, _
- FileName As String) As Recordset
- ' needs reference to Microsoft ActiveX Data object...
- Dim cn As ADODB.Connection
- Dim rs As Recordset
- Dim strSQL As String
- ' create Schema.ini file
- Open FilePath & "\Schema.ini" For Output As #1
- Print #1, "[" & FileName & "]"
- Print #1, "Format = " & ConvertDelimiter(Delim)
- Print #1, "ColNameHeader = True"
- Close #1
- Set cn = New ADODB.Connection
- Set rs = New ADODB.Recordset
- cn.Open ("Provider=Microsoft.ACE.OLEDB.12.0;" & _
- "Data Source=" & FilePath & ";" & _
- "Extended Properties=""text;HDR=Yes;FMT=Delimited(;)"";")
- ' extended properties are overidden by schema.ini
- strSQL = "select * from " & FileName
- rs.Open strSQL, cn
- Set ReadCSV = rs
- End Function
- '
- Public Function ConvertDelimiter(Delim As String)
- Dim myDelim
- Select Case True
- Case Len(Delim) = 1
- myDelim = "Delimited(" & Delim & ")"
- Case UCase(Delim) = "TAB"
- myDelim = "TabDelimited"
- Case Else
- myDelim = "FixedLength"
- End Select
- ConvertDelimiter = myDelim
- End Function