CarlRostron
New Member
- Joined
- May 11, 2011
- Messages
- 26
I have no clue as to why when I read a CSV file into a recordset, the headers are not all being read. I get gaps in the headers for whatever reason. Attached below is the Function to load the recordset from the file. I have hard coded Hdr to "No" in the connection string.
The below is how I output the resultset:
This has stumped me for a few hours. I have triple checked the CSV file and the first row in each file has definitely got headers. Some headers are loaded and output fine, others are just blank.
Please help.
Code:
Function QueryByID(tableName As String, fieldToQuery As String, Target As Long, Hdr As String) As Recordset
Dim strFilePath, strFileName, strQuery As String
Dim oFSObj, oConn As Object
Dim oRs As Recordset
Dim f, lastRow As Integer
theUser = GetUserName
theFileName = "C:\Documents and Settings\" & theUser & "\My Documents\Reporting\" & tableName
Set oFSObj = CreateObject("SCRIPTING.FILESYSTEMOBJECT")
strFilePath = oFSObj.GetFile(theFileName).ParentFolder.Path
strFileName = oFSObj.GetFile(theFileName).Name
'Open an ADO connection to the folder specified
Set oConn = CreateObject("ADODB.CONNECTION")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strFilePath & ";" & _
"Extended Properties=""text;HDR=No;FMT=Delimited(,)"";"
Set oRs = CreateObject("ADODB.RECORDSET")
'Now actually open the text file and import into Excel
If (Target = -1) Then
strQuery = "SELECT * FROM [" & strFileName & "];"
Else
'Now actually open the text file and import into Excel
strQuery = "SELECT * FROM [" & strFileName & "] WHERE [" & fieldToQuery & "] = " & Target
End If
'strQuery = "SELECT * FROM [" & strFileName & "]"
oRs.Open strQuery, oConn
'MsgBox oConn
'PrintQueryResults
Set QueryByID = oRs
End Function
The below is how I output the resultset:
Code:
Sub OutputResultSet(aTable As String)
Dim row, col, i, j As Integer
row = 1
col = 1
ThisWorkbook.Sheets(aTable).Activate
Sheets(aTable).Cells.ClearContents
rs.MoveFirst
Do While Not rs.EOF
For j = 1 To rs.Fields.Count
Cells(row, col).Value = rs.Fields(j - 1)
col = col + 1
Next j
rs.MoveNext
row = row + 1
col = 1
Loop
End Sub
This has stumped me for a few hours. I have triple checked the CSV file and the first row in each file has definitely got headers. Some headers are loaded and output fine, others are just blank.
Please help.