I have an Access 2010 database with all tables linked to SQL Server 2014 tables. I have an Excel 2010 (.xlsx) file (though it starts as a .csv, and I could leave it that way), that I need to import into a SQL Server table via VBA code. I know that there are import tools available to do this, however, I have 20+ XLS files per month to import, and would rather have an automated method of doing this.
All my VBA code resides in the Access database, and all the examples of VBA code I've been able to find are for pushing data from Excel (i.e. the code is in Excel) not pulling from Access (i.e. the code is in Access).
I would prefer to do it with a single INSERT INTO AccessTable SELECT FROM ExcelRange
query instead of reading Excel row by row, and I need to do some transformation on the Excel data before it's inserted.
What I have so far:
Private Sub TransferData(ByVal Company As String, ByVal Address As String, ByVal XLName As String)
Dim Con As ADODB.Connection
Dim SQLString As String
SQLString = "INSERT INTO SatSurvey " & _
"(ClinicID, Method, CollectionDate, Duration, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q17, Q18, Q19, Q20, Q21, Q22, Physician, Nurse, MedAst) " & _
"SELECT " & _
"('clinic name', IDFormat, IDendDate, IDtime, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q17, Q18, Q19, Q20, Q21, Q22, NZ(Q9s1,1), NZ(Q9s2,1), NZ(Q9s3,1)) " & _
" FROM [Excel 12.0;HDR=Yes;Database=" & XLName & "]." & Address
Set Con = New ADODB.Connection
' Con.ConnectionString = "Datasource=" & CurrentProject.Connection
Con.ConnectionString = CurrentProject.Connection
' Con.Properties(9).Value = "Extended Properties='Excel 12.0 Xml;HDR=YES';"
' Con.Provider = "Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0 Xml;HDR=YES';"
Con.Open
Con.Execute SQLString
End Sub
As you can see, I've tried a few different options to get things working. This seems to work the best except that I am now getting:
Run-time error '-2147467259 (80004005)':
The Database has been placed in a state by user 'Admin' on machine 'MINIT-EGHJSAU' that prevents it from being opened or locked.
The machine name indicated is my machine. Since the code is running from within Access on my machine, it seems logical that I would have had the database open.
I'm not tied to doing it this way, so any fixes or alternate suggestions are welcome.