Reputation: 145
I'm completely new to Visual Basic and I now need to take a program that is entirely constructed in VB6 and add the ability to import a large set of records in bulk from an excel file into the current SQL Database. all of the examples I have found online are confusing and require hard-coding of the file name (ex. Using document As New Spreadsheet() document.LoadFromFile("SimpleReport.xls")) yet this needs to be called by a user anytime they get a new set of records so I need the excel file name to be specified at time of import.
How do I import from excel to SQL using VB6? Can I make a variable for the excel filename or does the string value of the filename have to be hard coded? If I can make a variable can/should I add set and get to it in order to specify the filename? Thanks
Upvotes: 0
Views: 6154
Reputation: 27842
With a 32 bit Machine (O/S):
Dim cn As ADODB.Connection
Dim strSQL As String
Dim lngRecsAff As Long
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\test\myfile.xls;" & _
"Extended Properties=Excel 8.0"
'Import by using Jet Provider.
strSQL = "SELECT * INTO [odbc;Driver={SQL Server};" & _
"Server=<server>;Database=<database>;" & _
"UID=<user>;PWD=<password>].MyTable " & _
"FROM [MySheet$]"
Debug.Print strSQL
cn.Execute strSQL, lngRecsAff, adExecuteNoRecords
Debug.Print "Records affected: " & lngRecsAff
cn.Close
Set cn = Nothing
Microsoft KB : 321686 has more ideas.
Upvotes: 1