I have created an Excel Sheet that does some lookups to format data that needs to be inserted into another table. This Excel Workbook needs to be given to some users that are free to add some new rows, and then need to be able to hit an «Insert Into Database» button and have the records transformed and inserted as new records into a SQL Table. I am using Excel 2010 and SQL Server 2008. I have a connection to the DB as I am using it to pull some data back in order to verify the new rows being added, but I’m not sure how to then insert the data back.
Excellll
5,5494 gold badges38 silver badges55 bronze badges
asked Sep 22, 2010 at 9:24
You can do a lot with ADO:
Dim cn As New ADODB.Connection
''You should probably change Activeworkbook.Fullname to the
''name of your workbook
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& ActiveWorkbook.FullName _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
cn.Open strCon
s = "INSERT INTO [ODBC;Description=TEST;DRIVER=SQL Server;" _
& "SERVER=Server;Trusted_Connection=Yes;" _
& "DATABASE=test].SomeTable ( Col1, Col2, Col3, Col4 ) " _
& "SELECT a.Col1, a.Col2, a.Col3, a.Col4 " _
& "FROM [Sheet2$] a " _
& "LEFT JOIN [ODBC;Description=TEST;DRIVER=SQL Server;" _
& "SERVER=Server;Trusted_Connection=Yes;" _
& "DATABASE=test].SomeTable b ON a.Col1 = b.Col1 " _
& "WHERE b.Col1 Is Null"
cn.Execute s
You can also use the ACE connection: http://www.connectionstrings.com/ or OPENROWSET and an SQL Server connection. In all cases, you may have problems with mixed data types in columns, depending on your registry settings (http://forum.lessthandot.com/viewtopic.php?f=17&t=12043&p=59669&hilit=excel#p59669)
answered Sep 22, 2010 at 10:28
FionnualaFionnuala
90.1k7 gold badges110 silver badges148 bronze badges
1
I have found out that within a macro, you can create an ADO connection by adding a reference to the «Microsoft ActiveX Data Objects 6.0 Library». Once you have opened a connection within the Macro, you can create your insert statement and execute it via using the connection.Execute(statement) method:
Dim item as String = "Insert Into MyTable(ColA,ColB) VALUES('Foo', 'Bar')"
Dim thisCon As New ADODB.Connection
thiscon.Open("ConnectionString")
thisCon.Execute (item)
SeanC
15.6k5 gold badges45 silver badges65 bronze badges
answered Sep 22, 2010 at 10:29
BenBen
3,92612 gold badges53 silver badges87 bronze badges
After modifying the data in excel, need to generate Update statements, which will be executed by pressing the button «update». As a result, will be executed Update and Insert statements. Then have to send a query to refresh the data in Excel.(imho)
answered Sep 22, 2010 at 9:42
Zoitc2014Zoitc2014
2991 silver badge8 bronze badges
seun asked in an old post of mine, Interfacing with MySQL via Excel; whether it’s possible to submit data from Excel into MySQL.
Yes, it is very much possible to do this. In fact, I’ve written a tutorial on how to do this with the help of VBA.
First, we create the table that we will use to store the data. The SQL statement below will create our sample table called tutorial. Just copy and paste it into your favourite MySQL IDE or phpMyAdmin.
CREATE TABLE IF NOT EXISTS `tutorial` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) NOT NULL,
`author` varchar(255) NOT NULL,
`price` float(4,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Now that we’ve created the table, it’s time to store some data in it. The data must come from a source. In this example, I’ve created a list of book titles, along with the author and price of each book. Just copy the table below and paste it into an Excel worksheet.
Title | Author | Price |
---|---|---|
How to Win Friends and Influence People | Dale Carnegie | 7.99 |
The Magic of Thinking Big | David Schwartz | 10.17 |
The Richest Man in Babylon | George S. Clason | 6.99 |
As a Man Thinketh | James Allen | 9.95 |
The Power of Your Subconcious Mind | Dr. Joseph Murphy | 7.49 |
The Magic of Believing | Claude M. Bristol | 6.99 |
It Works | R.H. Jarrett | 3.00 |
Write It Down, Make It Happen: Knowing What You Want and Getting It | Henriette Anne Klauser | 10.52 |
The Attractor Factor: 5 Easy Steps For Creating Wealth (Or Anything Else) From the Inside Out | Joe Vitale | 11.53 |
The Science of Getting Rich | Wallace D. Wattles | 11.20 |
Now rename that sheet as Books. If you haven’t displayed your Visual Basic and Control Toolbox toolbars yet, now is a good time to do so. Go to the View top menu and navigate to Toolbars. Make sure Visual Basic and Control Toolbox are checked.
I prefer to place the toolbars at the top panel area so they’re out of the way of my Excel spreadsheet. You might want to do the same.
Next, click on the Properties icon of the Control Box toolbar and set the name of the Booksworksheet as wsBooks. You’ll get something like the screenshot below:
Now it’s on to some programming. But before we even start typing a single line of code, we need to understand what we’re trying to achieve with our code:
- Connect to the local MySQL database server
- Use the demo database
- Insert each line of the Books table into the tutorial database we created earlier
Connecting to the Database Server and Selecting the Correct Database
As we will be using VBA to perform our data insertion, we need a method to connect to the database server and ensure we’ve selected the correct database where the data will be inserted into.
There are three components necessary for us to perform MySQL database manipulation using VBA:
- MySQL Connector/ODBC
- Microsoft ActiveX Data Objects (ADO) Library
- The correct connection string to access the MySQL database
For this tutorial, I’m using MySQL Connector/ODBC 5.1. You can download it here. For Windows users, grab the MSI Installer version and just double click the file and go through the installation screen.
You’ll also need to reference to the Microsoft ActiveX Data Objects Library in your Excel Workbook. Fire up the Visual Basic Editor using Alt-F11. Go to the Tools top menu item of the Visual Basic Editor and choose References.
In the list of references, check the Microsoft ActiveX Data Objects 2.8 Library. Refer to the following screenshot:
Next, we will then start coding. The first thing we should do is to write a Sub procedure
to connect to the database. This will be done using an ADODB connection.
First we need to declare the variable for the ADODB connection. Make sure you’ve double-clicked the wsBooks worksheet in the Project Explorer (if you can’t see it, press Ctrl-R). It should bring out a code window for that sheet.
In that sheet, enter the following code:
Dim oConn As ADODB.Connection
Private Sub ConnectDB()
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _
"SERVER=localhost;" & _
"DATABASE=yourdatabase;" & _
"USER=yourdbusername;" & _
"PASSWORD=yourdbpassword;" & _
"Option=3"
End Sub
You should replace yourdatabase, yourdbusername and yourdbpassword with your database name, your database username and the database password accordingly.
Test your ConnectDB Sub procedure by putting the cursor anywhere between the Sub statement and press F5 (this runs the Sub procedure). If an error popup appears, check that your MySQL service is running and that you’ve referenced to the Microsoft ActiveX Data Objects 2.8 Library.
Once the ConnectDB Sub procedure is working, we will code the Sub procedure to perform data insertion. Before that, we need to create a data sanitizing function to escape single quotes before inserting them into the database. This is necessary because improper quote escaping will cause data insertion to fail.
Here are the codes for the esc function
that will escape single quotes from data to be inserted:
Function esc(txt As String)
esc = Trim(Replace(txt, "'", "'"))
End Function
And now for the Sub procedure to perform data insertion:
Dim rs As ADODB.Recordset
Private Sub InsertData()
Set rs = New ADODB.Recordset
ConnectDB
With wsBooks
For rowCursor = 2 To 11
strSQL = "INSERT INTO tutorial (author, title, price) " & _
"VALUES ('" & esc(.Cells(rowCursor, 1)) & "', " & _
"'" & esc(.Cells(rowCursor, 2)) & "', " & _
esc(.Cells(rowCursor, 3)) & ")"
rs.Open strSQL, oConn, adOpenDynamic, adLockOptimistic
Next
End With
End Sub
Now run the InsertData Sub procedure and you will see that it will insert the data from line 2 to line 11 of the Books worksheet into the tutorial table.
Hope this tutorial has given you a basic understanding on how to insert data into a MySQL database from Microsoft Excel using VBA. If you have any questions, just drop a comment below.
Tags: Microsoft, MySQL, Smoking
Hi ,
I am new to excel vba and i have absolutely no idea of how to achieve this.
i want to insert and update a sql server table using excel macro.
currently i have done it for the update can someone please help me in adding the insertion code.
here is the update code below:-
‘General variables we’ll need
Public con As ADODB.Connection
Public bIgnoreChange As Boolean
Dim pk As New Collection
Dim oldValue As Variant
Dim nRecordCount As Integer
Private Sub Workbook_Deactivate()
If Not (con Is Nothing) Then
con.Close
Set con = Nothing
End If
End Sub
Function IsInPrimaryKey(name As String)
For Each pki In pk
If (pki = name) Then
IsInPrimaryKey = True
Exit Function
End If
Next pki
IsInPrimaryKey = False
End Function
Function MakeSQLText(data As Variant)
If (IsNumeric(data)) Then
MakeSQLText = data
Else
MakeSQLText = «‘» & Replace(data, «‘», «»») & «‘»
End If
End Function
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
‘ Let’s retrieve the data from the SQL Server table with the same name as the sheet
bIgnoreChange = True
Set con = New ADODB.Connection
con.Provider = «sqloledb»
sConnectionString = «Server=D90SC6Q1SQLEXPRESS;Database=BIClients;UID=BIClients;Pwd=Rumbl31nJungl3»
con.Open sConnectionString
‘ Clean up old Primary Key
While (pk.Count > 0)
pk.Remove 1
Wend
‘ Try to retrieve the primary key information
On Error GoTo NoCon
Set rs = con.Execute(«SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kcu ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME WHERE tc.CONSTRAINT_TYPE = ‘PRIMARY KEY’ AND tc.TABLE_NAME
= ‘» & Sh.name & «‘»)
‘ Fill up the primary key infomration
While (Not rs.EOF)
pk.Add CStr(rs(0))
rs.MoveNext
Wend
‘ Clean up the sheet’s contents
Sh.UsedRange.Clear
‘ Now get the table’s data
Set rs = con.Execute(«SELECT fkGroupID,fkProjectID,[Outage Start Date],[Outage Stop Date],[Man Hour Lost],[Outage Cost],[fkReasonCategoryId] FROM » & Sh.name)
‘ Set the name of the fields
Dim TheCells As Range
Set TheCells = Sh.Range(«A1»)
For i = 0 To rs.Fields.Count — 1
TheCells.Offset(0, i).Value = rs.Fields(i).name
Next i
‘ Get value for each field
nRow = 1
While (Not rs.EOF)
For i = 0 To rs.Fields.Count — 1
TheCells.Offset(nRow, i).Value = rs(i)
Next
rs.MoveNext
nRow = nRow + 1
Wend
nRecordCount = nRow — 1
bIgnoreChange = (pk.Count = 0) And (nRecordCount > 0)
Exit Sub
NoCon:
con.Close
Set con = Nothing
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
‘ No loops, and don’t do nothing if there’s no connection
If bIgnoreChange Or con Is Nothing Then
Exit Sub
End If
‘ Is something different?
If (Target.Value = oldValue) Then
‘ No change
oldValue = Application.ActiveCell.Value
Exit Sub
End If
‘ Don’t allow changes in the column names or outside of the table borders
‘If Target.Row < 2 Or Sh.Cells(1, Target.Row).Text = «» Or Sh.Cells(1, Target.Column) = «» Or (Target.Row > nRecordCount + 1) Then
‘ Target.Value = oldValue
‘oldValue = Application.ActiveCell.Value
‘MsgBox «You can only edit items inside the table»
‘Exit Sub
‘End If
‘ Is this change is in a primary key column — if so, we can’t edit it
If (IsInPrimaryKey(Sh.Cells(1, Target.Column).Text)) Then
Target.Value = oldValue
oldValue = Application.ActiveCell.Value
MsgBox «This column is a part of the primary key, so it cannot be changed»
Exit Sub
End If
‘ Build the primary key from the data in this row
Dim Names As Range
Set Names = Sh.Range(«A1»)
nColumn = 0
sWhere = «»
While (Names.Offset(0, nColumn).Text <> «»)
If (IsInPrimaryKey(Names.Offset(0, nColumn).Text)) Then
If (sWhere <> «») Then
sWhere = sWhere & » AND «
End If
sWhere = sWhere & Sh.Cells(1, nColumn + 1).Text & » = » & MakeSQLText(Sh.Cells(Target.Row, nColumn + 1))
End If
nColumn = nColumn + 1
Wend
‘ Update the server!
sSQL = «UPDATE » & Sh.name & » SET » & «[» & Sh.Cells(1, Target.Column).Text & «]» & » = » & MakeSQLText(Target.Text) & » WHERE » & sWhere
con.Execute sSQL
oldValue = Application.ActiveCell.Value
End Sub
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If (Not bIgnoreChange) Then
‘ Remember the old value
oldValue = Application.ActiveCell.Value
End If
End Sub
Santt
Introduction
There are two ways to import SQL Server data into Microsoft Excel using VBA:
- To create a QueryTable connected to a database table using Excel or VBA.
- To insert database data to a range using ADO Recordset or Excel add-ins.
The QueryTable object has a native Excel feature to refresh data.
To refresh data inserted using ADO, just insert the data again.
There are two ways to export Excel data to SQL Server using VBA:
- To use ADO.
- To use Excel add-ins that allow saving data and support VBA integration.
You can download the example and continue reading when you try the code.
Download Example
The attached VBA code example works in Microsoft Excel 2003-2016.
The example works with data in Microsoft Azure SQL Database. So, you can test the solution right after download.
Before to continue
This article was written in June 2011. It contains the tested code that you can use. I have a lot of thanks.
I would like to recommend you to take a look at my e-book «Excel Applications. 10 Steps for VBA Developers.»
You can also download the workbook examples and the SaveToDB add-in used as a free VBA library.
With the SaveToDB add-in, you can create more functional VBA applications with fewer efforts.
For example, you can save data changes from Excel to a database using a single call like GetAddIn().Save.
E-book
E-book Examples
SaveToDB Add-In
Table of Contents
- Introduction
- SQL Server Data Import to Excel using QueryTable
- SQL Server Data Import to Excel using ADO
- SQL Server Data Import to Excel using SaveToDB Add-In
- Excel Data Export to SQL Server using ADO
- Excel Data Export to SQL Server using SaveToDB Add-In
- Connection String Functions
- Conclusion
- See Also
- Download
SQL Server Data Import to Excel using QueryTable
Function ImportSQLtoQueryTable
The function creates a native Excel QueryTable connected to the OLE DB data source specified by the conString parameter.
The result is nearly the same as using the standard Excel connection dialog box.
Function ImportSQLtoQueryTable(conString As String, query As String, target As Range) As Integer On Error Resume Next Dim ws As Worksheet Set ws = target.Worksheet Dim address As String address = target.Cells(1, 1).address ' Procedure recreates ListObject or QueryTable If Not target.ListObject Is Nothing Then ' Created in Excel 2007 or higher target.ListObject.Delete ElseIf Not target.QueryTable Is Nothing Then ' Created in Excel 2003 target.QueryTable.ResultRange.Clear target.QueryTable.Delete End If If Application.Version >= "12.0" Then ' Excel 2007 or higher With ws.ListObjects.Add(SourceType:=0, Source:=Array("OLEDB;" & conString), _ Destination:=Range(address)) With .QueryTable .CommandType = xlCmdSql .CommandText = StringToArray(query) .BackgroundQuery = True .SavePassword = True .Refresh BackgroundQuery:=False End With End With Else ' Excel 2003 With ws.QueryTables.Add(Connection:=Array("OLEDB;" & conString), _ Destination:=Range(address)) .CommandType = xlCmdSql .CommandText = StringToArray(query) .BackgroundQuery = True .SavePassword = True .Refresh BackgroundQuery:=False End With End If ImportSQLtoQueryTable = 0 End Function ' Source: http://support.microsoft.com/kb/816562 Function StringToArray(Str As String) As Variant Const StrLen = 127 Dim NumElems As Integer Dim Temp() As String Dim i As Integer NumElems = (Len(Str) / StrLen) + 1 ReDim Temp(1 To NumElems) As String For i = 1 To NumElems Temp(i) = Mid(Str, ((i - 1) * StrLen) + 1, StrLen) Next i StringToArray = Temp End Function
Code comments:
- The query parameter can contain a SELECT or EXECUTE query.
- The resulting data will be inserted starting from the top left cell of the target range.
- If the target range contains a ListObject or QueryTable object, it will be deleted, and a new object will be created instead.
If you need to change the query only, just change the QueryTable.CommandText property. - Pay attention to the .SavePassword = True line.
Microsoft Excel stores passwords without encryption.
If possible, use the trusted connection. However, it is not supported by Microsoft Azure SQL Database yet.
Test Code of SQL Server Data Import to Excel using QueryTable
Sub TestImportUsingQueryTable() Dim conString As String conString = GetTestConnectionString() Dim query As String query = GetTestQuery() Dim target As Range Set target = ThisWorkbook.Sheets(1).Cells(3, 2) Select Case ImportSQLtoQueryTable(conString, query, target) Case Else End Select End Sub
SQL Server Data Import to Excel using ADO
Function ImportSQLtoRange
The function inserts SQL Server data to the target Excel range using ADO.
Function ImportSQLtoRange(conString As String, query As String, target As Range) As Integer On Error Resume Next ' Object type and CreateObject function are used instead of ADODB.Connection, ' ADODB.Command for late binding without reference to ' Microsoft ActiveX Data Objects 2.x Library ' ADO API Reference ' https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/ado-api-reference?view=sql-server-ver16 ' Dim con As ADODB.Connection Dim con As Object Set con = CreateObject("ADODB.Connection") con.ConnectionString = conString ' Dim cmd As ADODB.Command Dim cmd As Object Set cmd = CreateObject("ADODB.Command") cmd.CommandText = query cmd.CommandType = 1 ' adCmdText ' The Open method doesn't actually establish a connection to the server ' until a Recordset is opened on the Connection object con.Open cmd.ActiveConnection = con ' Dim rst As ADODB.Recordset Dim rst As Object Set rst = cmd.Execute If rst Is Nothing Then con.Close Set con = Nothing ImportSQLtoRange = 1 Exit Function End If Dim ws As Worksheet Dim col As Integer Set ws = target.Worksheet ' Column Names For col = 0 To rst.Fields.Count - 1 ws.Cells(target.row, target.Column + col).Value = rst.Fields(col).Name Next ws.Range(ws.Cells(target.row, target.Column), _ ws.Cells(target.row, target.Column + rst.Fields.Count)).Font.Bold = True ' Data from Recordset ws.Cells(target.row + 1, target.Column).CopyFromRecordset rst rst.Close con.Close Set rst = Nothing Set cmd = Nothing Set con = Nothing ImportSQLtoRange = 0 End Function
Code comments:
- The query parameter can contain a SELECT or EXECUTE query.
- The resulting data will be inserted starting from the top left cell of the target range.
- Using Object types and the CreateObject function instead of direct use of ADO types
lets to avoid setting ActiveX Data Objects 2.x Library references on user computers.
This code works in Microsoft Excel 2003-2016. - Always use Set Nothing statements for ADODB.Connection and ADODB.Recordset objects to free resources.
Test Code of SQL Server Data Import to Excel using ADO
Sub TestImportUsingADO() Dim conString As String conString = GetTestConnectionString() Dim query As String query = GetTestQuery() Dim target As Range Set target = ThisWorkbook.Sheets(2).Cells(3, 2) target.CurrentRegion.Clear Select Case ImportSQLtoRange(conString, query, target) Case 1 MsgBox "Import database data error", vbCritical Case Else End Select End Sub
SQL Server Data Import to Excel using SaveToDB Add-In
The SaveToDB add-in allows connecting to databases, to text files, and the web using Data Connection Wizard, and supports OLE DB, ODBC, .NET and internal providers.
You can reload data using the Reload button at the ribbon or in the Context menu, or from VBA macros.
However, the add-in does not support connecting to new data sources from macros.
The add-in can save a lot of developer time when you need to implement changing query parameters.
You can modify the parameters by setting new values to named cells like Range(«Company») = «ABC».
You can learn about this feature in the attached SaveToDB examples for VBA developers.
Procedure TestImportUsingSaveToDB
The procedure reloads active table data.
The table is a native Excel ListObject connected using the Data Connection Wizard.
Sub TestImportUsingSaveToDB() Dim addIn As COMAddIn Dim addInObj As Object Set addIn = Application.COMAddIns("SaveToDB") Set addInObj = addIn.Object addInObj.Load End Sub
Code comments:
If the table is an Excel ListObject connected to a database using OLE DB or ODBC, then the action is the same as ListObject.QueryTable.Refresh BackgroundQuery:=False.
In other cases (the web and file connections or databases through .NET providers), the add-in refreshes data using internal procedures. Moreover, the macro remains the same.
Excel Data Export to SQL Server using ADO
Function ExportRangeToSQL
The function exports the sourceRange data to a specified database table.
The optional beforeSQL code is executed before exporting, and the optional afterSQL code is executed after exporting.
The following logic of the export process is used in the example:
- Delete all data from a temporary import table.
- Export Excel data to the empty temporary import table.
- Update desired tables from the temporary import table data.
Specially developed stored procedures are used in the first and third steps.
You can adapt them to your task.
Moreover, a universal code is used to transfer Excel data to a destination table.
Function ExportRangeToSQL(sourceRange As Range, conString As String, table As String, _ Optional beforeSQL = "", Optional afterSQL As String) As Integer On Error Resume Next ' Object type and CreateObject function are used instead of ADODB.Connection, ' ADODB.Command for late binding without reference to ' Microsoft ActiveX Data Objects 2.x Library ' ADO API Reference ' https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/ado-api-reference?view=sql-server-ver16 ' Dim con As ADODB.Connection Dim con As Object Set con = CreateObject("ADODB.Connection") con.ConnectionString = conString con.Open ' Dim cmd As ADODB.Command Dim cmd As Object Set cmd = CreateObject("ADODB.Command") ' BeginTrans, CommitTrans, and RollbackTrans Methods (ADO) ' http://msdn.microsoft.com/en-us/library/ms680895(v=vs.85).aspx Dim level As Long level = con.BeginTrans cmd.CommandType = 1 ' adCmdText If beforeSQL > "" Then cmd.CommandText = beforeSQL cmd.ActiveConnection = con cmd.Execute End If ' Dim rst As ADODB.Recordset Dim rst As Object Set rst = CreateObject("ADODB.Recordset") With rst Set .ActiveConnection = con .Source = "SELECT * FROM " & table .CursorLocation = 3 ' adUseClient .LockType = 4 ' adLockBatchOptimistic .CursorType = 0 ' adOpenForwardOnly .Open ' Column mappings Dim tableFields(100) As Integer Dim rangeFields(100) As Integer Dim exportFieldsCount As Integer exportFieldsCount = 0 Dim col As Integer Dim index As Integer For col = 0 To .Fields.Count - 1 index = 0 index = Application.Match(.Fields(col).Name, sourceRange.Rows(1), 0) If index > 0 Then exportFieldsCount = exportFieldsCount + 1 tableFields(exportFieldsCount) = col rangeFields(exportFieldsCount) = index End If Next If exportFieldsCount = 0 Then ExportRangeToSQL = 1 Goto ConnectionEnd End If ' Fast read of Excel range values to an array ' for further fast work with the array Dim arr As Variant arr = sourceRange.Value ' The range data transfer to the Recordset Dim row As Long Dim rowCount As Long rowCount = UBound(arr, 1) Dim val As Variant For row = 2 To rowCount .AddNew For col = 1 To exportFieldsCount val = arr(row, rangeFields(col)) If IsEmpty(val) Then Else .Fields(tableFields(col)) = val End If Next Next .UpdateBatch End With rst.Close Set rst = Nothing If afterSQL > "" Then cmd.CommandText = afterSQL cmd.ActiveConnection = con cmd.Execute End If ExportRangeToSQL = 0 ConnectionEnd: con.CommitTrans con.Close Set cmd = Nothing Set con = Nothing End Function
Code comments:
- The preliminary column mappings are used for fast transferring Excel range column data to a Recordset column.
- Excel data types are not verified.
- Using Object types and the CreateObject function instead of direct use of ADO types
lets to avoid setting ActiveX Data Objects 2.x Library references on user computers.
This code works in Microsoft Excel 2003-2016. - Always use Set Nothing statements for ADODB.Connection and ADODB.Recordset objects to free resources.
Test Code of Excel Data Export to SQL Server
The temporary dbo04.ExcelTestImport table is used for inserting Excel data.
This table is cleared before exporting by the dbo04.uspImportExcel_Before stored procedure.
The dbo04.uspImportExcel_After stored procedure updates the source dbo04.ExcelTest table with values from dbo04.ExcelTestImport.
This technique simplifies the Excel part of an application but requires additional database objects and server side coding.
Sub TestExportUsingADO() Dim conString As String conString = GetTestConnectionString() Dim table As String table = "dbo04.ExcelTestImport" Dim beforeSQL As String Dim afterSQL As String beforeSQL = "EXEC dbo04.uspImportExcel_Before" afterSQL = "EXEC dbo04.uspImportExcel_After" Dim ws As Worksheet Set ws = ThisWorkbook.ActiveSheet Dim qt As QueryTable Set qt = GetTopQueryTable(ws) Dim sourceRange As Range If Not qt Is Nothing Then Set sourceRange = qt.ResultRange Else Set sourceRange = ws.Cells(3, 2).CurrentRegion End If Select Case ExportRangeToSQL(sourceRange, conString, table, beforeSQL, afterSQL) Case 1 MsgBox "The source range does not contain required headers", vbCritical Case Else End Select ' Refresh the data If Not qt Is Nothing Then Call RefreshWorksheetQueryTables(ws) ElseIf ws.Name = ws.Parent.Worksheets(1).Name Then Else Call TestImportUsingADO End If End Sub
The called RefreshWorksheetQueryTables procedure updates all worksheet QueryTables and ListObjects.
Sub RefreshWorksheetQueryTables(ws As Worksheet) On Error Resume Next Dim qt As QueryTable For Each qt In ws.QueryTables qt.Refresh BackgroundQuery:=True Next Dim lo As ListObject For Each lo In ws.ListObjects lo.QueryTable.Refresh BackgroundQuery:=True Next End Sub
The called GetTopQueryTable function returns the most top QueryTable object connected to a database.
Function GetTopQueryTable(ws As Worksheet) As QueryTable On Error Resume Next Set GetTopQueryTable = Nothing Dim lastRow As Long lastRow = 0 Dim qt As QueryTable For Each qt In ws.QueryTables If qt.ResultRange.row > lastRow Then lastRow = qt.ResultRange.row Set GetTopQueryTable = qt End If Next Dim lo As ListObject For Each lo In ws.ListObjects If lo.SourceType = xlSrcQuery Then If lo.QueryTable.ResultRange.row > lastRow Then lastRow = lo.QueryTable.ResultRange.row Set GetTopQueryTable = lo.QueryTable End If End If Next End Function
Excel Data Export to SQL Server using SaveToDB Add-In
The SaveToDB add-in allows saving data changes from Excel to databases.
You can save data using the Save button at the ribbon or from VBA macros.
The simplest scenario is saving changes to a single target table. It works without coding.
Moreover, you can load data from tables, views, or stored procedures.
If you need to save the data to multiple normalized tables, you have to use stored procedures
for INSERT, UPDATE, and DELETE operations. It is not so hard.
Procedure TestExportUsingSaveToDB
The macro saves data changes of the active table to a database and reloads the data.
Sub TestExportUsingSaveToDB() Dim addIn As COMAddIn Dim addInObj As Object Set addIn = Application.COMAddIns("SaveToDB") Set addInObj = addIn.Object addInObj.Save End Sub
Code comments:
The SaveToDB add-in makes a lot of work behind the scene.
It saves table metadata, a copy of loaded data, and data changes on hidden sheets.
You can even close the workbook. When the Save action is called, it builds and sends
INSERT, UPDATE and DELETE statements (or specified stored procedures) to a database.
You can learn hidden sheets using the SaveToDB, Options, Developer Options tab,
and generated SQL commands using the SaveToDB, Save, View Save Changes SQL menu item.
Connection String Functions
The example contains several useful functions for working with connection strings.
Function OleDbConnectionString
If the Username parameter is empty, the function returns an OLE DB connection string for trusted connection.
Function OleDbConnectionString(Server As String, Database As String, _ Username As String, Password As String) As String If Username = "" Then OleDbConnectionString = "Provider=SQLOLEDB.1;Data Source=" & Server _ & ";Initial Catalog=" & Database _ & ";Integrated Security=SSPI;Persist Security Info=False;" Else OleDbConnectionString = "Provider=SQLOLEDB.1;Data Source=" & Server _ & ";Initial Catalog=" & Database _ & ";User ID=" & Username & ";Password=" & Password & ";" End If End Function
Function OdbcConnectionString
If the Username parameter is empty, the function returns an ODBC connection string for trusted connection.
Function OdbcConnectionString(Server As String, Database As String, _ Username As String, Password As String) As String If Username = "" Then OdbcConnectionString = "Driver={SQL Server};Server=" & Server _ & ";Trusted_Connection=Yes;Database=" & Database Else OdbcConnectionString = "Driver={SQL Server};Server=" & Server _ & ";UID=" & Username & ";PWD=" & Password & ";Database=" & Database End If End Function
Conclusion
You can use the attached example code to import-export data between Microsoft Excel and SQL Server.
The code works fine with Microsoft SQL Server 2005-2016 and Microsoft Azure SQL Database, and in Microsoft Excel 2003-2016.
You can adapt it to another database platforms like MySQL, Oracle, or DB2 as the code uses OLE DB and ODBC connections.
You can also use the SaveToDB add-in as a database layer starting Excel 2007.
SaveToDB allows implementing projects with fewer efforts as it solves database layer tasks from the box.
See Also
- Microsoft Office Development
- ADO API Reference
- How to import data from Microsoft SQL Server into Microsoft Excel
- Using SaveToDB Add-In as VBA Library
Download
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS
Contact US
Thanks. We have received your request and will respond promptly.
Log In
Come Join Us!
Are you a
Computer / IT professional?
Join Tek-Tips Forums!
- Talk With Other Members
- Be Notified Of Responses
To Your Posts - Keyword Search
- One-Click Access To Your
Favorite Forums - Automated Signatures
On Your Posts - Best Of All, It’s Free!
*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.
Posting Guidelines
Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Students Click Here
Insert From Excel Recordset to SQL Server tableInsert From Excel Recordset to SQL Server table(OP) 29 Feb 08 10:05 Hi, I am trying to insert values in an excel sheet located on the local computer into Database on a server. This is what I have so far in the excel macro.. Set ConnDB = New ADODB.Connection ConnDB.ConnectionString = «Driver={SQL Server};Server=PLPST1209;User ID=abc;Password=abc123;Database=Customer_Info» ‘open xls connection Connxls.Open «Provider=Microsoft.Jet.OLEDB.4.0;» & _ ‘open recordset I need help Inserting the Excel recordset Rst into table Customer_info on SQL Server? Can I insert the whole recordset at once like «Insert into Customer_info Select * from » & Rst in Excel VBA? Thanks. Red Flag SubmittedThank you for helping keep Tek-Tips Forums free from inappropriate posts. |
Join Tek-Tips® Today!
Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.
Here’s Why Members Love Tek-Tips Forums:
- Talk To Other Members
- Notification Of Responses To Questions
- Favorite Forums One Click Access
- Keyword Search Of All Posts, And More…
Register now while it’s still free!
Already a member? Close this window and log in.
Join Us Close