The reason I'm using importing entire worksheet but I need named range Excel_Fcast.
Could I post Xl 2003 code so I can see if I can extract new ideas to make this work?
Biz
I think you were on the right track with what you were doing earler. I have successfully tested the code below using an Excel 2003 file and SQL Server 2000 database. It will copy data from the named range
Forecast and create a new table on the SQL database named
FORECAST_TABLE. I believe that the same code could also be used to copy data from an Excel 2003 file to a SQL Server 2005 or 2008 database table, although I cannot test this as I don't have either of those database available for testing.
Do you have access to the SQL Query Analyzer application? If so, you can test the query part without using VBA by just doing something like this:
SELECT *
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;HDR=YES;Database=C:\temp\test.xls',
'select * from Forecast');
Once you have got the query working in Query Analyzer then you will be able to implement it in your VBA. In order to get it to work with Excel 2007 files you will need to change the connection string e.g.
SELECT *
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0 Xml;HDR=YES;Database=C:\temp\test.xlsx',
'SELECT * FROM Forecast');
However, if you try that then you will most likely come back to the issue of it complaining that it cannot find te ACE.OLEDB.12 driver and if that is the case then you will need to refer back to what I posted earlier.
Anyway, here's the code for pulling the data from an XLS file.
Code:
Sub CopyFromExcelToSQLServer()
Dim cn As ADODB.Connection
Dim sConn As String
Dim cmd As ADODB.Command
Dim sSQL As String
Set cn = CreateObject("ADODB.Connection")
'I have changed my actual connection details to x's - you will need to update for your actual connection.
sConn = "Provider=sqloledb;Server=xxx;Database=NORTHWIND;User Id=xx;Password=xx"
cn.Open sConn
sSQL = "SELECT * INTO FORECAST_TABLE FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0'," & _
"'Excel 8.0;HDR=YES;Database=C:\temp\test.xls'," & _
"'select * from Forecast');"
cn.Execute sSQL
cn.Close
Set cn = Nothing
End Sub