You are on page 1of 2

Excel-SQL Server Import-Export Using VBA

Description of the example files:

excel_sql_server.bas - source VBA module


excel-sql-server.xls - test workbook for Excel 2003
excel-sql-server.xlsm - test workbook for Excel 2007/2010/2013/2016

excel-sql-server.xlsm includes also an example of the SaveToDB add-in.

Usage:

The example uses an existing database hosted in Microsoft Azure SQL Database.

Just open a workbook and click the Import and Export buttons.

You must have an active Internet connection.

The example shows two techniques for importing data:

1. Using QueryTable object


2. Using ADO

and two techniques for exporting data:

1. Using ADO
2. Using the SaveToDB add-in

Here is the basic code for importing data using the QueryTable object:

With ws.ListObjects.Add(SourceType:=0, Source:=Array("OLEDB;" & conString), _


Destination:=Range(address))

With .QueryTable
.CommandType = xlCmdSql
.CommandText = Array(query)
End With
End With

Here is the basic code for importing data using ADO:

Set con = CreateObject("ADODB.Connection")


con.ConnectionString = conString

Set cmd = CreateObject("ADODB.Command")


cmd.CommandText = query

Dim rst As Object


Set rst = cmd.Execute

ws.Cells(target.row + 1, target.Column).CopyFromRecordset rst

Here is the basic code for exporting data using ADO:


Set con = CreateObject("ADODB.Connection")
con.ConnectionString = conString

Set cmd = CreateObject("ADODB.Command")

If beforeSQL > "" Then


cmd.CommandText = beforeSQL
cmd.Execute
End If

Set rst = CreateObject("ADODB.Recordset")

With rst
.Source = "SELECT * FROM " & table
.Open

For row = 2 To sourceRange.Rows.Count


.AddNew

' Fill the column data ...


Next
.UpdateBatch
End With

If afterSQL > "" Then


cmd.CommandText = afterSQL
cmd.Execute
End If

Here is the basic code for exporting data using the SaveToDB add-in:

Dim addIn As COMAddIn


Dim addInObj As Object

Set addIn = Application.COMAddIns("SaveToDB")


Set addInObj = addIn.Object

addInObj.Save

You may use the SaveToDB add-in as a free VBA library.


You may download it at https://www.savetodb.com.

Copyright 2011-2017 Sergey Vaselenko, www.excel-sql-server.com

You might also like