Solved

Insert records into an sql database with vba macro from excel range

Posted on 2010-09-17
7
747 Views
Last Modified: 2012-05-10
I have a excel spreadsheet that needs to be regularly imported in an sql database.

I would like the user to be able to run a personal macro to update this data into the database then I have some other macros to run.

I can loop through each on the lines and inset the records one by one but this takes quite a while - I would like to be able to insert a range from the spreadsheet into a table in an SQL database in one process. Is this possible.



0
Comment
Question by:donhannam
7 Comments
 
LVL 65

Expert Comment

by:rockiroads
ID: 33706002
Should be doable but what version excel and what database are you using?

code would be something along these lines

create a database connection (can use ado or dao)
iterate thru your rows
create the sql statement to insert
run this sql statement
next row until no more
close database
0
 

Author Comment

by:donhannam
ID: 33706015
Thanks.

I am using excel 2003 and MSL database 2005.

I have tried to iterate through rows one at a time but a lot of info and takes a very long time.

Looking for a quicker way to import a range at once.
0
 
LVL 81

Accepted Solution

by:
zorvek (Kevin Jones) earned 500 total points
ID: 33706022
Use this SQL syntax for speedy bulk inserts:

INSERT INTO TableName(FieldName1,FieldName2)
UNION ALL
SELECT data, data
UNION ALL
SELECT data, data
...
GO

Kevin
0
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
LVL 65

Expert Comment

by:rockiroads
ID: 33706043
found an easier way which might be helpful to you. let me know if this works else I will come up with the way I described


http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_23958162.html
0
 
LVL 65

Expert Comment

by:rockiroads
ID: 33706049
the adodb parameters should match the column you want to insert to in terms of datatype as well
0
 
LVL 33

Expert Comment

by:Norie
ID: 33709561
You shouldn't need to loop through each 'record' in Excel to append the data to a table in the database.

You should be able to write code that would treat the data in Excel in much the same way as a table in the database.

Then with the correct SQL you should be able to append the data in one go, just like you would in the database.

Here's some sample code which runs from VBA.

Please note this is pretty incomplete - I've even marked the file 'not perfect but it seems to be going somewhere.'.

Oh, forgot to mention this is for Excel to SQL Server.
    Dim cn As ADODB.Connection
    Dim strSQL As String
    Dim lngRecsAff As Long
    Set cn = New ADODB.Connection
    cn.Open "Provider=SQLOLEDB;Data Source=NORIE-TOSH;" & _
        "Initial Catalog=StaffLevel;Trusted_Connection=yes"

    'Import by using OPENDATASOURCE.
    strSQL = "SELECT * INTO XLImport1 FROM " & _
        "OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0', " & _
        "'Data Source=C:\Users\Norie\Documents\Excel Stuff\Mock Data\AccountNos.xls;" & _
        "Extended Properties=Excel 8.0')...[tblAccounts$]"
    Debug.Print strSQL
    cn.Execute strSQL, lngRecsAff, adExecuteNoRecords
    Debug.Print "Records affected: " & lngRecsAff

    'Import by using OPENROWSET and object name.
    strSQL = "SELECT * INTO XLImport2 FROM " & _
        "OPENROWSET('Microsoft.Jet.OLEDB.4.0', " & _
        "'Excel 8.0;Database=C:\Users\Norie\Documents\Excel Stuff\Mock Data\AccountNos.xls', " & _
        "[TblAccounts$])"
    Debug.Print strSQL
    cn.Execute strSQL, lngRecsAff, adExecuteNoRecords
    Debug.Print "Records affected: " & lngRecsAff

    'Import by using OPENROWSET and SELECT query.
    strSQL = "SELECT * INTO XLImport3 FROM " & _
        "OPENROWSET('Microsoft.Jet.OLEDB.4.0', " & _
        "'Excel 8.0;Database=C:\Users\Norie\Documents\Excel Stuff\Mock Data\AccountNos.xls, " & _
        "'SELECT * FROM [tblAccounts$]')"
    Debug.Print strSQL
    cn.Execute strSQL, lngRecsAff, adExecuteNoRecords
    Debug.Print "Records affected: " & lngRecsAff

    cn.Close
    Set cn = Nothing

Open in new window

0
 

Author Closing Comment

by:donhannam
ID: 33729859
Thanks for all the comments - Solution by zorvek was real quick and easy to do.
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Approximate matching with VLOOKUP and MATCH seems to me to be a greatly under-used technique, and one which is vital for getting good performance out of large lookups. Until recently I would always have advised using an exact match for simplicity an…
Convert between Excel file formats (.XLS, .XLSX, .XLSM) with/without macro option David Miller (dlmille) Intro Over this past Fall, I've had the opportunity to see several similar requests and have developed a couple related solutions associate…
Graphs within dashboards are meant to be dynamic, representing data from a period of time that will change each time the dashboard is updated with new data. Rather than update each graph to point to a different set within a static set of data, t…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question