Solved

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

Posted on 2010-09-17
7
741 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
time format showing wrong 12 51
Problem to With line 4 41
DBF to ... Converter 5 40
Excel 2016 - Black cell borders 11 27
Dealing with unintended Excel Active-X resizing quirks (VBA code simulates "self correction") David Miller (dlmille) Intro Not everyone is a fan of Active-X controls in spreadsheets (as opposed to the UserForm approach, the older Form controls …
Introduction While answering a recent question (http:/Q_27311462.html), I created an alternative function to the Excel Concatenate() function that you might find useful.  I tested several solutions and share the results in this article as well as t…
The viewer will learn how to simulate a series of sales calls dependent on a single skill level and learn how to simulate a series of sales calls dependent on two skill levels. Simulating Independent Sales Calls: Enter .75 into cell C2 – “skill leve…
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…

910 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now