Dividing a table in 2 separate tables by parsing a string - sql

I have a table that roughly looks like this:
the 1300 and 850 stand for frequency on wich these fibre cables are checked
The real problem is that the 1300 and 850 aren't set values. In a different file they could be "100" and "320", so I can't just look for "850" or "1300" to seperate the entries.
There are a few things that I can be sure of:
There's always 2 different frequencies (let's call them "A" and "B" from now on)
There are always the same amount of "A" entries as there are "B" entries
the string is always a variations of \<A>\<A>nm_<LocationName>_<CoreNumber>.SOR
What I would like to have is 2 seperate tables, 1 for all of the "A" entries and one for the "B" entries.
How can I do this?
It doesn't matter if I have to use SQL or VBA
Edit:
By looking around on the internet, I have gained a general idea of how I would like this to work:
open the table as a recordset.
search every line for the value between the \'s. Example: \<value>\
for every new value between the \ \
fill the first table with all entries that have the first value (in our example 1300)
I just have no clue how to translate this into code, the person that knows how to do this, easy points

So I may have made is sound way easier and bit off more than I could chew, but I was able to create something that works on my MS Access with a sample Database. I did all this from just quick Google-fu so it may not be as elegant as an expert. But it works. This only takes the existing table and creates new tables, but if you need help transferring data then I can tweak this.
Dim myR As Recordset
Dim strSQL As String
Dim strMOD As String
Dim strFULL As String
Dim strNEW As String
Dim charPOS As Integer
Dim strLEN As Integer
Dim strTABLES() As Variant
Dim dbs As DAO.Database
Dim tdfloop As DAO.TableDef
Dim i As Long
Dim j As Long
Dim strNAME As String
Dim alrEXIST As Boolean
i = 0
Set dbs = CurrentDb
With dbs
For Each tdfloop In .TableDefs
ReDim Preserve strTABLES(0 To i)
strTABLES(UBound(strTABLES)) = tdfloop.Name
i = i + 1
Next tdfloop
End With
Set dbs = Nothing
'select all the rows in your table so we can add them to recordset
strSQL = "SELECT * FROM Files"
'create your recordset
Set myR = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)
'now to access each row we use a loop
'if you're not sure the field names, you can access them like this:
'myR.Fields(1).Value
'or if you do know the field name then this
'myR![Filename]
myR.MoveFirst 'This just makes sure you're starting from the first record
Do Until myR.EOF = True
strFULL = myR![FileName] 'set this to string so it can be worked with
strLEN = Len(strFULL) 'gets the length of the string aka filename
strMOD = Right(strFULL, strLEN - 1) 'removes the first \
charPOS = InStr(strMOD, "\") 'gets the positiong of the next \
strNEW = Mid(strMOD, 1, charPOS - 1) 'gets the substring from left to \
'use this to check and see if the name is a table already
For j = 0 To i - 1
If strNEW = strTABLES(j) Then
alrEXIST = True 'boolean created for if table exists
End If
Next
'if not a table, create a table
If alrEXIST = False Then
DoCmd.RunSQL "CREATE TABLE " & strNEW & " ([Field1] text(255), [Field2] text(255))"
End If
alrEXIST = False 'reset value to false
myR.MoveNext 'Move to the next record before restarting the loop
Loop
Set myR = Nothing

Thanks to TKEyi60's answer, I was put on the right track. Had to tweak the code here and there to come to this solution:
Public Function SplitTable()
Dim SQL As String
Dim strMOD As String
Dim strFULL As String
Dim strNEW As String
Dim charPOS As Integer
Dim strLEN As Integer
Dim i As Long
Dim j As Long
Dim alrEXIST As Boolean
Dim strTABLES() As Variant
Dim Rcst As DAO.Recordset
Dim dbs As DAO.Database
Dim tdfloop As DAO.TableDef
i = 0
Set dbs = CurrentDb
For Each tdfloop In dbs.TableDefs
ReDim Preserve strTABLES(0 To i)
strTABLES(UBound(strTABLES)) = tdfloop.Name
i = i + 1
Next tdfloop
Set dbs = Nothing
'Select all the rows in the table so they can be added to a Recordset
SQL = " SELECT * FROM tblTotaalVerlies"
Set Rcst = CurrentDb.OpenRecordset(SQL, dbOpenDynaset)
Rcst.MoveFirst
Do Until Rcst.EOF = True
strFULL = Rcst![FileName] 'set this to string so it can be worked with
strLEN = Len(strFULL) 'gets the length of the filename
strMOD = Right(strFULL, strLEN - 1) 'removes the first \
charPOS = InStr(strMOD, "\") 'gets the positiong of the next \
strNEW = Mid(strMOD, 1, charPOS - 1)
'use this to check and see if the name is a table already
For j = 0 To i - 1
If strNEW = strTABLES(j) Then
alrEXIST = True 'boolean created for if table exists
End If
Next j
'if not a table, create a table
If alrEXIST = False Then
DoCmd.RunSQL "CREATE TABLE " & strNEW & " ([Filename] varchar(32), [Verlies] varchar(32))"
'Renew tabledef array
i = i + 1
ReDim Preserve strTABLES(0 To i - 1)
strTABLES(UBound(strTABLES)) = strNEW
End If
alrEXIST = False 'reset value to false
Rcst.MoveNext 'Move to the next record before restarting the loop
Loop
Set Rcst = Nothing
End Function

Related

MS Access update query that select columns from table1 and updates row in table2

I need a query to execute whenever a Form closes (on Sub Form_Unload) that updates T2.id_from_t1 based on T1.Name = T2.Name. So it has to convert rows to column and match the result with the Name.
Is it possible to do this with just one SQL query or VBA?
T1 T2
ID | Name ID | Name | id_from_t1
1 Bob 1 Bob 1, 2
2 Bob 2 Joe 3, 4
3 Joe 3 Mark 5
4 Joe 4 Bill 6
5 Mark
6 Bill
Here's how I solved my problem
Sub to iterate through the table to update (T2)
Public Sub tableToUpdate()
Dim strSQL
Dim DataB As Database
Dim rs As Recordset
Dim t2_id As Integer
Dim values As String
Set DataB = CurrentDb()
Set rs = DataB.OpenRecordset("Select id from T2")
Do While Not rs.EOF
t2_id = rs("ID")
Parks = GetListOptimal("Select T1.id as t1_id from T1 Where T1.id_t2 = " & t2_id, ", ", "")
strSQL = "UPDATE T2 SET T2.t1_ids = '" & values & "' WHERE T2.id = " & t2_id
DataB.Execute strSQL, dbFailOnError
t2_id = 0
values = ""
rs.MoveNext
Loop
rs.Close
DataB.Close
Set rs = Nothing
Set DataB = Nothing
End Sub
GetListOptimal is the function to generate the comma separated values
' Concatenate multiple values in a query. From:
' https://stackoverflow.com/questions/5174362/microsoft-access-condense-multiple-lines-in-a-table/5174843#5174843
'
' Note that using a StringBuilder class from here:
' https://codereview.stackexchange.com/questions/67596/a-lightning-fast-stringbuilder/154792#154792
' offers no code speed up
Public Function GetListOptimal( _
SQL As String, _
Optional fieldDelim As String = ", ", _
Optional recordDelim As String = vbCrLf _
) As String
Dim dbs As Database
Dim rs As Recordset
Dim records() As Variant
Dim recordCount As Long
' return values
Dim ret As String
Dim recordString As String
ret = ""
recordString = ""
' index vars
Dim recordN As Integer
Dim fieldN As Integer
Dim currentField As Variant
' array bounds vars
Dim recordsLBField As Integer
Dim recordsUBField As Integer
Dim recordsLBRecord As Integer
Dim recordsUBRecord As Integer
' get data from db
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset(SQL)
' added MoveLast to get the real number of rows
If rs.recordCount > 0 Then
rs.MoveLast
recordCount = rs.recordCount
rs.MoveFirst
End If
' Guard against no records returned
If recordCount = 0 Then
GetListOptimal = ""
Exit Function
End If
records = rs.GetRows(recordCount)
' assign bounds of data
recordsLBField = LBound(records, 1) ' should always be 0, I think
recordsUBField = UBound(records, 1)
recordsLBRecord = LBound(records, 2) ' should always be 0, I think
recordsUBRecord = UBound(records, 2)
' FYI vba will loop thorugh every For loop at least once, even if
' both LBound and UBound are 0. We already checked to ensure that
' there is at least one record, and that also ensures that
' there is at least one record. I think...
' Can a SQL query return >0 records with 0 fields each?
'Primo giro (per non aggiungere virgola)
Dim first As Boolean
first = True
For recordN = recordsLBRecord To recordsUBRecord
For fieldN = recordsLBField To recordsUBField
' Virgola prima del record solo se non siamo al primo e ultimo giro
If first = False Then
recordString = recordString & fieldDelim
Else
first = False
End If
' records is indexed (field, record) for some reason
currentField = records(fieldN, recordN)
' Guard against null-valued fields
If Not IsNull(currentField) Then
recordString = recordString & CStr(currentField)
End If
Next fieldN
' Only add recordDelim after at least one record
If ret <> "" Then
ret = ret & recordDelim
End If
ret = ret & recordString
recordString = "" ' Re-initialize to ensure no old data problems
Next recordN
' adds final recordDelim at end output
' not sure when this might be a good idea
' TODO: Implement switch parameter to control
' this, rather than just disabling it
' If ret <> "" Then
' ret = ret & recordDelim
' End If
' Cleanup db objects
Set dbs = Nothing
Set rs = Nothing
GetListOptimal = ret
Exit Function
End Function
Sources used:
VBA Update table/recordset in Access using Loop with values from another table/recordset?
Access 2010 VBA query a table and iterate through results
Microsoft Access condense multiple lines in a table (Daniel S's answer with some improvements)

MS Access Query to find gaps in sequential numbers when numbers are stored in Short Text field

I have a table (tblParts) with a PartNumber field (Short Text) which stores 6 digit part numbers for parts belonging to several families. The families are denoted by the first 2 digits of the part number (00, 01, 02, etc).
(NOTE: I did not create this table and am not able to change it at this time)
I need to find gaps in the numbering in order to fill in unused part numbers. If I have a project starting that needs 6 consecutive part numbers in a specific family, I want to find the first unused number in the first gap of that size or greater within that family.
Here is a small subset of the data.
PartNumber
020001
020002
020003
020004
020005
020006
020007
020009
020010
020011
020012
020013
020014
020019
020101
If I needed a single number, the query should find 020008. If I needed 3 numbers, it should find 0200015 and if I needed 10 numbers it should find 020020.
My SQL knowledge is very limited but I am trying to learn. I realize this would be much easier if the information was stored properly but I have no control over it.
I once wrote an article on the subject:
Find and Generate Missing Values in an Access Table
but that will fill up any gap until all new numbers were established. So, that code will need an expansion with an outer loop to ensure juxtaposed numbers at all times.
Private Sub btnSearch_Click()
' Read table/query sequentially to
' record all missing IDs.
' Fill a ListBox with missing values.
' A reference to Microsoft DAO must be
' present.
' Define search table or query.
Const cstrTable As String = "Orders"
Const cstrField As String = "OrderID"
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim lst As ListBox
Dim col As Collection
Dim strSQL As String
Dim strList As String
Dim lngLast As Long
Dim lngNext As Long
Dim lngMiss As Long
strSQL = "Select " & cstrField & "" _
& " From " & cstrTable & _
& " Order By 1;"
Set lst = Me!lstMissing
Set col = New Collection
Set dbs = CurrentDb
Set rst = dbs.OpenRecordset(strSQL)
If rst.RecordCount = 0 Then
'The recordset is empty.
'Nothing to do.
Else
lngLast = rst(cstrField).Value
rst.MoveNext
While rst.EOF = False
lngNext = rst(cstrField).Value
For lngMiss = lngLast + 1 To _
lngNext - 1
col.Add (lngMiss)
Next
lngLast = lngNext
rst.MoveNext
Wend
'Generate next value in sequence.
'Discard if collecting only
'missing values.
col.Add (lngLast + 1)
End If
rst.Close
'Populate list box from collection.
For lngMiss = 1 To col.Count
If Len(strList) > 0 Then
strList = strList & ";"
End If
strList = strList & col(lngMiss)
Debug.Print col(lngMiss)
Next
lst.RowSource = strList
Debug.Print strList
Set rst = Nothing
Set dbs = Nothing
Set col = Nothing
Set lst = Nothing
End Sub

Access database import from excel file fails when AssocID (first field) is mixed with integers and strings

I have an access database with vba code that is attempting to access an excel sheet and copy the data to a recordset using DAO.recordset. If all of the column (assocId) is integer the import works wonderfully if all are strings it works but if you have a mixed back (eg 111111 | Vinny | etc and then on row two you have JOE-1 | Joe | etc) the import will fail. It says "You cannot record your changes because a value you entered violates the settings defined for this table"
Here is the offending sub:
Public Sub LoadFileInfo()
'Load information from selected file
On Error GoTo ErrorHappened
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Integer
Dim lastTransType As String
Dim transactionCounter As Integer
Dim currentRecord As CurrentImportRecord
Dim wtf As Variant
Set db = CurrentDb()
Set rs = db.OpenRecordset(selectTransTypesSql & GetSetting("PayrollManualImportExportTransactionTypes") & ")")
ReDim transTypes(DCount("TransType", "MasterTransactionTypes", "IsActive <> 0")) As MasterTransactionTypes
rs.MoveFirst
Do While Not rs.EOF
'Add each transaction type and desc to the Private Type and increment the appropriate counter
GetMasterTransactionTypes rs!TransType, rs!TransDesc, i
rs.MoveNext
i = i + 1
Loop
rs.Close
Set db = OpenDatabase(importFileName, False, True, "Excel 12.0;HDR=Yes")
Set rs = db.OpenRecordset("SELECT * FROM " & "[" & GetSheetName(importFileName) & "$]" & " ORDER BY TransType")
rs.MoveLast
importFields = vbNullString
For i = 0 To rs.Fields.count - 1
importFields = importFields & rs.Fields(i).Name & ","
Next
fullImport = (rs.Fields.count > 4)
i = 0
transactionCounter = 1
lblFile.Caption = "File name: " & importFileName
Dim rowNum As Variant
rowNum = rs.RecordCount
wtf = rs.GetRows(rowNum)
ReDim ledgerEntries(rs.RecordCount) As PayrollLedgerImport
'Check to see if the recordset actually contains rows; if so push transaction objects to private type array
rs.MoveFirst
Do While Not rs.EOF
currentRecord.associateId = CStr(rs!assocId)
currentRecord.transactionType = rs!TransType
currentRecord.transactionNotes = CStr(rs!TransNotes)
If lastTransType = CStr(currentRecord.transactionType) Then
transactionCounter = transactionCounter + 1
Else
transactionCounter = 1
End If
If IsValidTransType(currentRecord.transactionType) Then
If Not fullImport Then
currentRecord.transactionAmount = rs!TransAmount
GetPayrollTransactions currentRecord.associateId, currentRecord.transactionType, currentRecord.transactionAmount, currentRecord.transactionNotes, i, transactionCounter
Else
currentRecord.transactionAmount = rs!TransAmt
GetPayrollTransactions currentRecord.associateId, currentRecord.transactionType, currentRecord.transactionAmount, currentRecord.transactionNotes, i, transactionCounter
End If
Else
MsgBox (currentRecord.transactionType & ": Not A Valid Transaction Type")
End If
lastTransType = rs!TransType
rs.MoveNext
i = i + 1
Loop
FormatFileInformationWindow
cmdImportFile.Enabled = True
End Sub
I've been at this for hours. I've tried casting all the columns when I take them in and I get the same issue. Works fine for all ints or all strings but in reality some of our employees have string and some have int for employee ID. I tried taking them all in as string converting where necessary but that didn't work either. Only thing that works is two sheets - one containing strings one containing ints.

Excel VBA checking if range of values exist in ODBC connected database

I am having an issue (otherwise I wouldn't be here) :)
In Excel I have a list of item numbers that need to be checked if they already exist in a database. At the moment the only way to do that is to run a query in a separate sheet to get all the item numbers (400,000+) which takes quite some time and has to be done each time.
I have started a vba query which goes through each cell that is selected and checks that value to see if it exist in the database. If it exist, the cell turns Red. If it doesn't exist, the cell turns green.
I'm not that great when it comes to querying databases using VBA so I used bits and pieces that I found online.
When I go to test it, Excel crashes and closes so I can't determine where its going wrong.
Public Sub CheckItemNoExist()
Dim DB As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim c As Range
Dim ItemNum As Variant
Dim bFound As Boolean
DB.Open "DSN=DBNAME;UID=****;PWD=****;"
Set rs = DB.OpenRecordset("SELECT [Inventory.ITM_NO] FROM [OAUSER.Inventory] WHERE [Inventory.ITM_NO]=" & ItemNum & ";", dbOpenDynaset)
For Each c In ActiveSheet.Selection
ItemNum = c.Value
bFound = Not rs.EOF
If bFound Then
c.Interior.Color = RGB(255, 0, 0)
Else
c.Interior.Color = RGB(0, 255, 0)
End If
Next
rs.Close
Set rs = Nothing
DB.Close
Set DB = Nothing
End Sub
Thank you!
Matt
I suggest you use an IN in your where clause to bring over all the items in the selection, then filter the recordset for each item to see if it found it. I don't have your data setup, so I used a truck database that I have handy. You should be able to convert
Sub CheckTruckExists()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sSql As String
Dim aInClause() As String
Dim rCell As Range
Dim vaTrucks As Variant
Dim i As Long
'Open a connection to the database
Set cn = New ADODB.Connection
cn.Open sCONNECTIONSTRING
'Get an array of values from the selection
vaTrucks = Selection.Value
'Increase the size of the one-dimensional array to match
ReDim aInClause(LBound(vaTrucks, 1) To UBound(vaTrucks, 1))
'Fill a one-dim array from the two-dim array so we can Join it
For i = LBound(vaTrucks, 1) To UBound(vaTrucks, 1)
aInClause(i) = vaTrucks(i, 1)
Next i
'Build the SQL statement and execute it
sSql = "SELECT ReportTruck FROM qryTrucks WHERE ReportTruck IN ('" & Join(aInClause, "','") & "')"
Set rs = New Recordset
Set rs = cn.Execute(sSql)
'Loop through the selected cells
For Each rCell In Selection.Cells
'clear the filter, then refilter the recordset on the filtered value
rs.Filter = adFilterNone
rs.Filter = "ReportTruck = '" & rCell.Value & "'"
'If the filter returned zero records, it's eof
If rs.EOF Then
rCell.Interior.Color = RGB(255, 0, 0)
Else
rCell.Interior.Color = RGB(0, 255, 0)
End If
Next rCell
End Sub
My ReportTruck field is a String, so I have to enclose all the trucks in my IN clause with single quotes. If you're looking for something other than a String, modify the Join to accommodate that data type.
Also, there's no error checking to makes sure the Selection is actually a Range object or that it contains more than one cell - both are necessary to avoid an error.

VBA Access: Import CSV with additonal header data

I am new to coding VBA. Was wondering if you all could help me? I have a CSV file which is structured as the following:
- First 22 rows cover the specfic header data(this all loads in one column in excel)
- column headers for table are in Row 23
- the data is actually located from row 24 onward.
What the code needs to do is insert this data in new table with the right column titles. Also while inserting it needs to input the file name and header data in the first few columns of the table.
So far I have imported the entire CSV into an array I believe:
See what I have so far:
Sub readCSV()
Dim fs As Object
Dim fso As New FileSystemObject
Dim tsIn As Object
Dim sFileIn, filename As String
Dim aryFile, aryHeader, aryBody As Variant
sFileIn = "C:\doc\test.csv"
Set filename = fso.GetFileName(sFileIn)
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1)
sTmp = tsIn.ReadAll
aryFile = Split(sTmp, vbCrLf)
For i = 1 To 22
aryHeader(1, i) = aryFile(i)
Next i
For i = 23 To UBound(aryFile)
aryBody(i) = Split(aryFile(i), ",")
DoCmd.RunSQL "INSERT INTO MAINS VALUES (filename,aryHeader(1),aryBody(i))"
Next i
End Sub
is this correct? Can anyone see of i am taking the right approach
UPDATE - recoded this a bit
Use DoCmd.TransferText instead of rolling out your own code:
http://msdn.microsoft.com/en-us/library/office/ff835958%28v=office.15%29.aspx
In your Import Specification, you can set the starting row.
See Skip first three lines of CSV file (using DoCmd?) in MS Access for more information!
Edit: The import specification can be changed to rename the fields etc. See http://www.access-programmers.com/creating-an-import-specification-in-access-2003.aspx (the Import wizard exists in Access 2007 as well) and the Advanced dialog specifically.
I was a bit irked by the use of multiple arrays in your code (which is super confusing, to me, anyway, because you are looking at counters everywhere) so I thought I would post an alternative for you. If you can do it your way, more power to you, but if you run into problems, you can try this. Code below is much more verbose, but may save you time in the future if you hand it off or even have to come back to it yourself and have no idea what is going on (lol):
Sub ReadCSV()
On Error GoTo ErrorHandler
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim fso As Scripting.FileSystemObject
Dim tst As Scripting.TextStream
Dim strFileName As String
Dim intCurrentLine As Integer
Dim strCurrentLine As String
Dim intHeaderRows As Integer
Dim strHeader As String
Dim strHeaderDelimInField As String
'Consider these your 'constants', so you don't come back to this code in a month
'and wonder what the random numbers mean.
intHeaderRows = 22 'Number of header rows in CSV.
strHeaderDelimInField = "~" 'The character(s) you want to separate each
'header line, in field.
strFileName = "C:\IrregularCSV.csv"
intCurrentLine = 1 'Keep track of which line in the file we are currently on.
'Next two lines get a reference to your table; will add data via DAO and not SQL,
'to avoid messy dynamic SQL.
Set db = CurrentDb()
Set rst = db.OpenRecordset("Mains", dbOpenDynaset)
Set fso = New Scripting.FileSystemObject
Set tst = fso.OpenTextFile(strFileName, ForReading)
'Instead of storing data in arrays, let's go through the file line by line
'and do the work we need to do.
With tst
Do Until .AtEndOfStream
strCurrentLine = .ReadLine
If intCurrentLine <= intHeaderRows Then
strHeader = strHeader & strHeaderDelimInField & strCurrentLine
Else
'Add the records via DAO here.
rst.AddNew
'In DAO, rst.Fields("FieldName") are the columns in your table.
rst.Fields("FileName") = strFileName
'Remove leading delimiter with Right.
rst.Fields("HeaderInfo") = Right(strHeader, Len(strHeader) - 1)
'Note that Split always returns a zero-based array
'and is unaffected by the Option Base statement.
'The way below is less efficient than storing
'the return of Split, but also less confusing, imo.
rst.Fields("Field1") = Split(strCurrentLine, ",")(0)
rst.Fields("Field2") = Split(strCurrentLine, ",")(1)
rst.Fields("Field3") = Split(strCurrentLine, ",")(2)
rst.Update
End If
intCurrentLine = intCurrentLine + 1
Loop
End With
tst.Close
rst.Close
ExitMe:
Set tst = Nothing
Set fso = Nothing
Set rst = Nothing
Set db = Nothing
Exit Sub
ErrorHandler:
Debug.Print Err.Number & ": " & Err.Description
GoTo ExitMe
End Sub
To be honest, I think there are a lot of gotchas to the way you are going about it. Not saying it won't work, because I think it can, but this method is more robust. An unexpected single quote won't ruin your work and using a data object to do the inserts is not prone (well, less, at least) to SQL injection issues. And I've done it with no persisted arrays. Anyway, some food for thought. Good luck.
this is what i ended up:
Sub ReadCSV2()
Dim fs As Object
Dim filename As String
Dim tsIn As Object
Dim sFileIn As String
Dim aryHeader, aryBody As Variant
Dim Text As String
Dim sqlcre As String
Dim sqlsta As String
sFileIn = "C:\test\test.csv"
filename = GetFilenameFromPath(sFileIn) 'function to get the file name
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1)
For i = 1 To 23
Tmps = tsIn.ReadLine
Next i
aryHeader = Split(Tmps, ",")
On Error Resume Next
DoCmd.RunSQL "DROP TABLE tempdata"
On Error GoTo 0
sqlcre = "CREATE TABLE tempdata ([Filename] Text,"
For k = LBound(aryHeader) To UBound(aryHeader)
sqlcre = sqlcre & "[" & aryHeader(k) & " " & k + 1 & "] Text,"
Next k
k = k - 1
sqlcre = Left(sqlcre, Len(sqlcre) - 13) & ")"
'Debug.Print k
'Debug.Print sqlcre
DoCmd.RunSQL sqlcre
DoCmd.SetWarnings False
While Not tsIn.AtEndOfStream
Tmps = tsIn.ReadLine
aryBody = Split(Tmps, ",")
sqlsta = "INSERT INTO tempdata VALUES ('" & filename & "','"
For M = LBound(aryBody) To UBound(aryBody)
sqlsta = sqlsta & Replace(aryBody(M), "'", "`") & "', '"
Next M
M = M - 1
Debug.Print M
If M < k Then
Text = ""
For i = 1 To (k - M)
Text = Text & "', '"
Next i
sqlsta = sqlsta & Text
End If
sqlsta = Left(sqlsta, Len(sqlsta) - 7) & ")"
'Debug.Print sqlsta
'Debug.Print k
DoCmd.RunSQL sqlsta
Wend
DoCmd.SetWarnings True
End Sub