BEST PRACTICES -> SQL with DAO

Irish_Griffin

Board Regular
Joined
Jan 16, 2009
Messages
138
Hi guys,
I've discovered excel can do SQL !!! It feels like I'm the primitive caveman discovering fire :laugh:

Well lets not talk about how much time I've wasted writing code that would have been soooooooo much easier in SQL :( .... Instead, lets talk about BEST PRACTICES using SQL in EXCEL :cool:

I would like to make this thread a good reference for others ( not much online surprisingly ). I'll make this a sweet thread if I can get the guru's help.

So first and foremost:
#1 - Is DAO the right choice ?

Remember to take learning one bite at a time:
QrUHZ.jpg
 
The tool
Code:
Sub SQL_to_Range(DB_location_name As String, SQL_Text As String, Target_Range As Range, With_Titles As Boolean)
' This code will run SQL on an existing table and results will be outputed to a new db table

'Opens a connection to the database File
Dim ADO_Connection As ADODB.connection
Set ADO_Connection = New ADODB.connection
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_location_name & ";"
ADO_Connection.Open (Connection_String)
Dim CMD As New ADODB.Command
Dim RS As ADODB.Recordset

CMD.ActiveConnection = ADO_Connection
CMD.CommandType = adCmdText
CMD.CommandText = SQL_Text
Set RS = CMD.Execute


Call RS2WS(RS, Target_Range, With_Titles)

'Clean up recordset object
RS.Close
Set RS = Nothing
'Close the connection so that computer resources are not used
ADO_Connection.Close
Set ADO_Connection = Nothing

End Sub

Calling the tool
Code:
'PREFORM SQL CODE AND PASTE INTO RANGE
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim DB_location_name As String ' Full path and file name of database
Dim Table_Name As String ' Name of db table to delete
Dim SQL_Text As String
Dim Target_Range As Range
Dim With_Titles As Boolean

Table_Name = "New_Table" '<------------------------------------------------- INPUT
DB_location_name = "C:\test.mdb"  '<---------------------------------------- INPUT
SQL_Text = "SELECT * FROM " & Table_Name & " WHERE [Part_type]='Seal'"  '<-- INPUT
Target_Sheet = "Output"  '<------------------------------------------------- INPUT
With_Titles = True '<------------------------------------------------------- INPUT

'RUN THE SQL TOOL                                                            =)
Set Target_Range = ThisWorkbook.Sheets(Target_Sheet).Cells(2, 2)

Call SQL_to_Range(DB_location_name, SQL_Text, Target_Range, With_Titles)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////
 
Upvote 0
What a mouthful.... "threadful" I guess... :stickouttounge:
fGqgj.jpg


LOL.... thats alot of code!! .... and this is only rev 1

CREATE A TABLE IN THE DB FROM AN ARRAY is on the way :cool:

PEACE
-Griff
 
Upvote 0
ugggggggggGGGGGGGG :mad:

Got pulled into some Bull $hit waste of time work...... wish idiots would do there job and pull there weight in this industry :crash:

OK.... be back to this project in a week :rolleyes: :(
 
Upvote 0
Array to Table:

The Tool:
Code:
Sub Array_to_DB_table(DB_location_name As String, New_Table_Name As String, Data_Array As Variant)

'Opens a connection to the database File
Dim Connection_String As String
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_location_name & ";"
Dim ADO_Connection As ADODB.connection
Set ADO_Connection = New ADODB.connection
ADO_Connection.Open (Connection_String)

Dim Column_Title As String
Dim SQL_Text As String
Dim i As Integer
Dim r As Integer
Dim c As Integer
Dim Colan As String
Dim Array_LB As Integer
Dim Array_UB As Integer
Dim Record_LB As Long
Dim Record_UB As Long

'delte table with same name if it exisits
SQL_Text = "DROP TABLE " & New_Table_Name
On Error Resume Next
    ADO_Connection.Execute SQL_Text
On Error GoTo 0

Array_UB = UBound(Data_Array)
Array_LB = LBound(Data_Array)
Record_UB = UBound(Data_Array, 2)
Record_LB = LBound(Data_Array, 2)

SQL_Text = "CREATE TABLE " & New_Table_Name & " ("

'This tool assumes text..... will improve later
'Place the titles into an array

For i = Array_LB To Array_UB
    Column_Title = Data_Array(i, Record_LB)
    'Check to see column titles meet criteria : No spaces and required text
    If Trim(Column_Title) = "" Then
        MsgBox ("Data Range has blank column titles.  Fix to execute the code.")
        GoTo The_End
    End If
    If Not InStr(1, Column_Title, " ") = 0 Then
        MsgBox ("One of the column titles has a space.  Fix to execute the code.")
        GoTo The_End
    End If
    SQL_Text = SQL_Text & "[" & Column_Title & "] Text(150) WITH Compression, "
Next


SQL_Text = Left(SQL_Text, Len(SQL_Text) - 2) & ")"
ADO_Connection.Execute SQL_Text


Colan = """"

'Loop through the Array record sets and paste into the table
For r = Record_LB + 1 To Record_UB
    SQL_Text = "INSERT INTO " & New_Table_Name & " VALUES("
    For c = Array_LB To Array_UB
        SQL_Text = SQL_Text & Colan & Data_Array(c, r) & Colan & ","
    Next
    SQL_Text = Left(SQL_Text, Len(SQL_Text) - 1)
    SQL_Text = SQL_Text & ")"
    ADO_Connection.Execute SQL_Text
Next

The_End:
'Close the connection so that computer resources are not used
ADO_Connection.Close
Set ADO_Connection = Nothing

End Sub

Calling the Tool:
Code:
'CREATE A TABLE IN THE DB FROM ARRAY (with first record titles)
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim i As Integer ' General counter
Dim New_Table_Name As String ' Name of table in database, no spaces
Dim DB_location_name As String ' Full path and file name of database
ReDim Data_Array(1 To 3, 1 To 100) As String

'A loop in code is best to create an array, but for simplicity we will use this example
'ARRAY FORMAT: Array(Column,Row) top Left starting at (0,0)
'You MUST create an array that top row contains the title for every column
Data_Array(1, 1) = "Name" ' COLUMN TITLE
Data_Array(1, 2) = "Mary"
Data_Array(1, 3) = "Joe"
Data_Array(1, 4) = "Bob"

Data_Array(2, 1) = "Eye_Color" ' COLUMN TITLE 'NOTE, no spaces for titles
Data_Array(2, 2) = "Blue"
Data_Array(2, 3) = "Brown"
Data_Array(2, 4) = "Hazel"


Data_Array(3, 1) = "Height" ' COLUMN TITLE
Data_Array(3, 2) = "6'2"
Data_Array(3, 3) = "5'6"
Data_Array(3, 4) = "4'9"


'Resize the array accordingly
ReDim Preserve Data_Array(1 To 3, 1 To 4) ' You can only change the range of the last array dimension


DB_location_name = "C:\test.mdb" '<----------------------------------------- INPUT
New_Table_Name = "New_Table" '<--------------------------------------------- INPUT
'RUN THE SQL TOOL                                                            =)
Call Array_to_DB_table(DB_location_name, New_Table_Name, Data_Array)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////
 
Upvote 0
The following function I found online was used within the SQL TO RANGE TOOL

Code:
Sub RS2WS(RS As ADODB.Recordset, TargetCell As Range, With_Titles As Boolean)
Dim f As Integer, r As Long, c As Long
    If RS Is Nothing Then Exit Sub
    If RS.State <> adStateOpen Then Exit Sub
    If TargetCell Is Nothing Then Exit Sub
    
    With Application
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .StatusBar = "Writing data from recordset..."
    End With
    
    With TargetCell.Cells(1, 1)
        r = .Row
        c = .Column
    End With
    
    With TargetCell.Parent
        .Range(.Cells(r, c), .Cells(.Rows.Count, c + RS.Fields.Count - 1)).Clear
        ' clear existing contents
        ' write column headers
        If With_Titles = True Then
            For f = 0 To RS.Fields.Count - 1
                On Error Resume Next
                .Cells(r, c + f).Formula = RS.Fields(f).Name
                On Error GoTo 0
            Next f
        Else
            r = r - 1
        End If
        
        ' write records
        On Error Resume Next
        RS.MoveFirst
        On Error GoTo 0
        Do While Not RS.EOF
            r = r + 1
            For f = 0 To RS.Fields.Count - 1
                On Error Resume Next
                .Cells(r, c + f).Formula = RS.Fields(f).Value
                On Error GoTo 0
            Next f
            RS.MoveNext
        Loop
        .Rows(TargetCell.Cells(1, 1).Row).Font.Bold = True
        .Columns("A:IV").AutoFit
    End With
    
    With Application
        .StatusBar = False
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With
End Sub
 
Upvote 0
Is it possible to pull the information out of a query instead of from tables? i have a union query that i run weekly and then copy/paste the info into excel.

i found an ADO demo in "Excel 2003 Power Programming with VBA" book that i have, but im not sure if posting the code that came along with it would violate some sort of board rules. any way, it is pulling the information from the one table in the database, instead of from a query.

Since the query is already set up to filter records & join tables the way that i want, i would think a data dump form here would be the easiest.

thoughts?
 
Upvote 0
Is it possible to pull the information out of a query instead of from tables? i have a union query that i run weekly and then copy/paste the info into excel.

i found an ADO demo in "Excel 2003 Power Programming with VBA" book that i have, but im not sure if posting the code that came along with it would violate some sort of board rules. any way, it is pulling the information from the one table in the database, instead of from a query.

Since the query is already set up to filter records & join tables the way that i want, i would think a data dump form here would be the easiest.

thoughts?



Hmmm.... a bit above my level....

I don't think you will be able to pull from a query. But you might be able to store the query in a record set and pull from that.....

Good luck, please feel free to contribute to the ADO knowledge on this thread :biggrin:
 
Upvote 0
The latest SQL tool box:

Code:
'  <<<<<<<<<<<<<<<<<<<<<<<<<<< EXCEL SQL TOOL KIT >>>>>>>>>>>>>>>>>>>>>>>>>>>
'  |                                                                        |
'  |  Created by:  Irish_Griffin and those at MrExcel.com                   |
'  |        Date:  Jan 10, 2010                                             |
'  |     Version:  1.1                                                      |
'  |                                                                        |
'  |  This file allows intermediate users to preform SQL                    |
'  |    functions from Excel using the "ADO" 2.8 API                        |
'  |  For a tutorial in SQL, visit the following site:                      |
'  |                             http://www.w3schools.com/SQl/default.asp   |
'  |                                                                        |
'  |  Here is the list of tools:                                            |
'  |   ->  CREATE A DATABASE                                                |
'  |   ->  DELETE A DATABASE                                                |
'  |   ->  CREATE A TABLE IN THE DB FROM A RANGE                            |
'  |   ->  CREATE A TABLE IN THE DB FROM AN ARRAY                           |
'  |   ->  DELETE A TABLE IN THE DB                                         |
'  |   ->  PREFORM SQL CODE TO GENERATE ARRAY WITH OUT TITLES               |
'  |   ->  PREFORM SQL CODE TO GENERATE ARRAY WITH TITLES                   |
'  |   ->  PREFORM SQL CODE AND PASTE INTO RANGE                            |
'  |                                                                        |
'  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


'IMPORTANT --> To change database server, you must modify ALL "Connection_String" in below code
'              For details see ->  www.w3schools.com/ado/ado_connect.asp  &  www.connectionstrings.com

Sub Create_DB(DB_Location_Name As String)
' This function can create either a local or network .mdb file for temporary or permenant use

Dim ADO_Catalog As ADOX.Catalog
Dim Connection_String As String
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_Location_Name & ";"
Set ADO_Catalog = New ADOX.Catalog

'Automaticly will delete previous file if present
On Error Resume Next
    Kill DB_Location_Name
On Error GoTo 0

ADO_Catalog.Create (Connection_String)

End Sub

Sub Delete_DB(DB_Location_Name As String)
'This function can delete a .mdb file

On Error Resume Next
    Kill DB_Location_Name
On Error GoTo 0

End Sub


Sub Range_to_DB_Table(DB_Location_Name As String, New_Table_Name As String, Data_Range As Range)
'This function takes a sheet and pastes it into a created database

'Opens a connection to the database File
Dim Connection_String As String
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_Location_Name & ";"
Dim ADO_Connection As ADODB.connection
Set ADO_Connection = New ADODB.connection
ADO_Connection.Open (Connection_String)

Dim Column_Title As String
Dim column_count As Integer
Dim SQL_Text As String
Dim i As Integer
Dim r As Integer
Dim c As Integer
Dim box As Range ' Pklace holder to scan through the original range
Dim Colan As String

'delte table with same name if it exisits
SQL_Text = "DROP TABLE " & New_Table_Name
On Error Resume Next
    ADO_Connection.Execute SQL_Text
On Error GoTo 0


column_count = Data_Range.Columns.Count

SQL_Text = "CREATE TABLE " & New_Table_Name & " ("

'This tool assumes text..... will improve later
'Place the titles into an array

c = Data_Range.Column

For i = 0 To column_count - 1
    Column_Title = Data_Range.Cells(1, i + 1).Value
    'Check to see column titles meet criteria : No spaces and required text
    If Trim(Column_Title) = "" Then
        MsgBox ("Data Range has blank column titles.  Fix to execute the code.")
        MsgBox (SQL_Text)
        GoTo The_End
    End If
    If Not InStr(1, Column_Title, " ") = 0 Then
        MsgBox ("One of the column titles has a space.  Fix to execute the code.")
        MsgBox (SQL_Text)
        'GoTo The_End
    End If
    SQL_Text = SQL_Text & "[" & Column_Title & "] Text(150) WITH Compression, "
Next

SQL_Text = Left(SQL_Text, Len(SQL_Text) - 2) & ")"

ADO_Connection.Execute SQL_Text

'Data upload into table
SQL_Text = "INSERT INTO " & New_Table_Name & " VALUES("
'Knowing that the first row contain titles we add 1 to the row
r = Data_Range.Row
First_Row = r
r = r + 1
Colan = """"
'For loop starts at the top left, crosses over to the right, drops a row and repeats
For Each box In Data_Range
    'If statement placed to skip first row that contians titles
    If First_Row < box.Row Then
    
        'Checks to see if a new row has started , thus the database needs the latest record uploaded
        If r <> box.Row Then
            'Triggered when the box value moves down a row , thus needing a record upload to the table
            If r > 1 Then
                SQL_Text = Left(SQL_Text, Len(SQL_Text) - 1)
                SQL_Text = SQL_Text & ")"
                ADO_Connection.Execute SQL_Text
            End If
            r = box.Row
            'Resets the initial SQL text string to upload new re
            SQL_Text = "INSERT INTO " & New_Table_Name & " VALUES("
        End If
    
        'Updates the SQL text
        SQL_Text = SQL_Text & Colan & box.Value & Colan & ","
    End If
Next

The_End:
'Close the connection so that computer resources are not used
ADO_Connection.Close
Set ADO_Connection = Nothing

End Sub


Sub Delete_DB_Table(DB_Location_Name As String, Table_Name As String)

'Opens a connection to the database File
Dim ADO_Connection As ADODB.connection
Set ADO_Connection = New ADODB.connection
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_Location_Name & ";"
ADO_Connection.Open (Connection_String)

Dim SQL_Text As String
SQL_Text = "DROP TABLE " & Table_Name

On Error Resume Next
    ADO_Connection.Execute SQL_Text
On Error GoTo 0

'Close the connection so that computer resources are not used
ADO_Connection.Close
Set ADO_Connection = Nothing

End Sub

Function SQL_to_Array_wo_Titles(DB_Location_Name As String, SQL_Text As String) As Variant
' This code will run SQL on an existing table and results will be outputed to a new db table

'Opens a connection to the database File
Dim ADO_Connection As ADODB.connection
Set ADO_Connection = New ADODB.connection
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_Location_Name & ";"
ADO_Connection.Open (Connection_String)
Dim CMD As New ADODB.Command
Dim RS As ADODB.Recordset

CMD.ActiveConnection = ADO_Connection
CMD.CommandType = adCmdText
CMD.CommandText = SQL_Text
Set RS = CMD.Execute

'Create the Array
SQL_to_Array_wo_Titles = RS.GetRows()

'Clean up recordset object
RS.Close
Set RS = Nothing
'Close the connection so that computer resources are not used
ADO_Connection.Close
Set ADO_Connection = Nothing

End Function



Function SQL_to_Array_w_Titles(DB_Location_Name As String, SQL_Text As String) As Variant
' This code will run SQL on an existing table and results will be outputed to a new db table

'Opens a connection to the database File
Dim ADO_Connection As ADODB.connection
Set ADO_Connection = New ADODB.connection
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_Location_Name & ";"
ADO_Connection.Open (Connection_String)
Dim CMD As New ADODB.Command
Dim RS As ADODB.Recordset
Dim Row_Count As Long
Dim Col_Count As Long

CMD.ActiveConnection = ADO_Connection
CMD.CommandType = adCmdText
CMD.CommandText = SQL_Text
Set RS = CMD.Execute

Col_Count = RS.Fields.Count

Row_Count = 0
RS.MoveFirst
Do While Not RS.EOF
    Row_Count = Row_Count + 1
    RS.MoveNext
Loop


ReDim My_Array(0 To Col_Count - 1, 0 To Row_Count) As Variant '1 not subtracted from row_count to allow room for titles
Dim r As Integer
Dim c As Integer

'Place titles on array
For c = 0 To Col_Count - 1
    On Error Resume Next
    My_Array(c, 0) = RS.Fields(c).Name
    On Error GoTo 0
Next

'copys data from recordset into array
r = 0
RS.MoveFirst
Do While Not RS.EOF
    r = r + 1
    For c = 0 To Col_Count - 1
        My_Array(c, r) = RS.Fields(c).Value
    Next
    RS.MoveNext
Loop

SQL_to_Array_w_Titles = My_Array

'Clean up recordset object
RS.Close
Set RS = Nothing
'Close the connection so that computer resources are not used
ADO_Connection.Close
Set ADO_Connection = Nothing

End Function



Sub SQL_to_Range(DB_Location_Name As String, SQL_Text As String, Target_Range As Range, With_Titles As Boolean)
' This code will run SQL on an existing table and results will be outputed to a new db table

'Opens a connection to the database File
Dim ADO_Connection As ADODB.connection
Set ADO_Connection = New ADODB.connection
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_Location_Name & ";"
ADO_Connection.Open (Connection_String)
Dim CMD As New ADODB.Command
Dim RS As ADODB.Recordset

CMD.ActiveConnection = ADO_Connection
CMD.CommandType = adCmdText
CMD.CommandText = SQL_Text
Set RS = CMD.Execute


Call RS2WS(RS, Target_Range, With_Titles)

'Clean up recordset object
RS.Close
Set RS = Nothing
'Close the connection so that computer resources are not used
ADO_Connection.Close
Set ADO_Connection = Nothing

End Sub

Sub RS2WS(RS As ADODB.Recordset, TargetCell As Range, With_Titles As Boolean)
Dim f As Integer, r As Long, c As Long
    If RS Is Nothing Then Exit Sub
    If RS.State <> adStateOpen Then Exit Sub
    If TargetCell Is Nothing Then Exit Sub
    
    With Application
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .StatusBar = "Writing data from recordset..."
    End With
    
    With TargetCell.Cells(1, 1)
        r = .Row
        c = .Column
    End With
    
    With TargetCell.Parent
        .Range(.Cells(r, c), .Cells(.Rows.Count, c + RS.Fields.Count - 1)).Clear
        ' clear existing contents
        ' write column headers
        If With_Titles = True Then
            For f = 0 To RS.Fields.Count - 1
                On Error Resume Next
                .Cells(r, c + f).Formula = RS.Fields(f).Name
                On Error GoTo 0
            Next f
        Else
            r = r - 1
        End If
        
        ' write records
        On Error Resume Next
        RS.MoveFirst
        On Error GoTo 0
        Do While Not RS.EOF
            r = r + 1
            For f = 0 To RS.Fields.Count - 1
                On Error Resume Next
                .Cells(r, c + f).Formula = RS.Fields(f).Value
                On Error GoTo 0
            Next f
            RS.MoveNext
        Loop
        .Rows(TargetCell.Cells(1, 1).Row).Font.Bold = True
        .Columns("A:IV").AutoFit
    End With
    
    With Application
        .StatusBar = False
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
    End With
End Sub

Sub Array_to_DB_table(DB_Location_Name As String, New_Table_Name As String, Data_Array As Variant)

'Opens a connection to the database File
Dim Connection_String As String
Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DB_Location_Name & ";"
Dim ADO_Connection As ADODB.connection
Set ADO_Connection = New ADODB.connection
ADO_Connection.Open (Connection_String)

Dim Column_Title As String
Dim SQL_Text As String
Dim i As Integer
Dim r As Integer
Dim c As Integer
Dim Colan As String
Dim Array_LB As Integer
Dim Array_UB As Integer
Dim Record_LB As Long
Dim Record_UB As Long

'delte table with same name if it exisits
SQL_Text = "DROP TABLE " & New_Table_Name
On Error Resume Next
    ADO_Connection.Execute SQL_Text
On Error GoTo 0

Array_UB = UBound(Data_Array)
Array_LB = LBound(Data_Array)
Record_UB = UBound(Data_Array, 2)
Record_LB = LBound(Data_Array, 2)

SQL_Text = "CREATE TABLE " & New_Table_Name & " ("

'This tool assumes text..... will improve later
'Place the titles into an array

For i = Array_LB To Array_UB
    Column_Title = Data_Array(i, Record_LB)
    'Check to see column titles meet criteria : No spaces and required text
    If Trim(Column_Title) = "" Then
        MsgBox ("Data Range has blank column titles.  Fix to execute the code.")
        GoTo The_End
    End If
    If Not InStr(1, Column_Title, " ") = 0 Then
        MsgBox ("One of the column titles has a space.  Fix to execute the code.")
        GoTo The_End
    End If
    SQL_Text = SQL_Text & "[" & Column_Title & "] Text(150) WITH Compression, "
Next


SQL_Text = Left(SQL_Text, Len(SQL_Text) - 2) & ")"
ADO_Connection.Execute SQL_Text


Colan = """"

'Loop through the Array record sets and paste into the table
For r = Record_LB + 1 To Record_UB
    SQL_Text = "INSERT INTO " & New_Table_Name & " VALUES("
    For c = Array_LB To Array_UB
        SQL_Text = SQL_Text & Colan & Data_Array(c, r) & Colan & ","
    Next
    SQL_Text = Left(SQL_Text, Len(SQL_Text) - 1)
    SQL_Text = SQL_Text & ")"
    ADO_Connection.Execute SQL_Text
Next

The_End:
'Close the connection so that computer resources are not used
ADO_Connection.Close
Set ADO_Connection = Nothing

End Sub
 
Upvote 0
Examples how to use the tool box:

Code:
'  <<<<<<<<<<<<<<<<<<<<<<<<<<< EXCEL SQL TOOL KIT >>>>>>>>>>>>>>>>>>>>>>>>>>>
'  |                                                                        |
'  |  Created by:  Irish_Griffin and MrExcel.com                            |
'  |        Date:  December 1, 2009                                         |
'  |     Version:  1.0                                                      |
'  |                                                                        |
'  |  This file allows intermediate users to preform SQL                    |
'  |    functions from Excel using the "ADO" 2.8 API                        |
'  |  For a tutorial in SQL, visit the following site:                      |
'  |                             http://www.w3schools.com/SQl/default.asp   |
'  |                                                                        |
'  |  Here is the list of tools:                                            |
'  |   ->  CREATE A DATABASE                                                |
'  |   ->  DELETE A DATABASE                                                |
'  |   ->  CREATE A TABLE IN THE DB FROM A WORKSHEET RANGE                  |
'  |   ->  CREATE A TABLE IN THE DB FROM AN ARRAY                           |
'  |   ->  DELETE A TABLE IN THE DB                                         |
'  |   ->  PREFORM SQL CODE TO GENERATE ARRAY WITH OUT TITLES               |
'  |   ->  PREFORM SQL CODE TO GENERATE ARRAY WITH TITLES                   |
'  |   ->  PREFORM SQL CODE AND PASTE INTO RANGE                            |
'  |                                                                        |
'  |  Instructions:                                                         |
'  |    1) Create a module with your code and "call" tool as shown below    |
'  |    2) Create Database ( permenate or temporary )                       |
'  |    3) Create Table on the Database                                     |
'  |    4) Learn SQL (queries, sorts, filters, mass updates, ect...)        |
'  |    5) Enjoy having SQL in Excel!!!!!  =-)                              |                                                     |
'  |                                                                        |
'  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>





Sub temporary_sub1()

'CREATE A DATABASE
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim DB_Location_Name As String

DB_Location_Name = "C:\test.mdb" '<----------------------------------------- INPUT
'RUN THE SQL TOOL                                                            =)
Call Create_DB(DB_Location_Name)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////

End Sub







Sub temporary_sub2()

'DELETE A DATABASE
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim DB_Location_Name As String

DB_Location_Name = "C:\test.mdb" '<----------------------------------------- INPUT
'RUN THE SQL TOOL                                                            =)
Call Delete_DB(DB_Location_Name)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////

End Sub







Sub temporary_sub3()

'CREATE A TABLE IN THE DB FROM RANGE
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim Data_Range As Range ' The range to be copied into the database
ReDim Column_Titles(1 To 100) As Variant ' The array to pass column titles, critical for SQL code
Dim i As Integer ' General counter
Dim New_Table_Name As String ' Name of table in database, no spaces
Dim DB_Location_Name As String ' Full path and file name of database

'Determine the range that will be pasted into the database table
'The first row MUST be the column names with no spaces, instead use "_"
Set Data_Range = ThisWorkbook.Worksheets("Input").Range("B2:K300")
'You must create an array that contains a name for every column in the range above
'For i = 1 To Data_Range.Columns.Count
'    Column_Titles(i) = ThisWorkbook.Worksheets("Input").Cells(1, i) '<------ INPUT
'Next
'ReDim Preserve Column_Titles(1 To Data_Range.Columns.Count)

DB_Location_Name = "C:\test.mdb" '<----------------------------------------- INPUT
New_Table_Name = "New_Table" '<--------------------------------------------- INPUT
'RUN THE SQL TOOL                                                            =)
Call Range_to_DB_Table(DB_Location_Name, New_Table_Name, Data_Range)
Set Data_Range = Nothing
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////



End Sub







Sub temporary_sub4()

'DELETE A TABLE IN THE DB
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim DB_Location_Name As String ' Full path and file name of database
Dim Table_Name As String ' Name of db table to delete

DB_Location_Name = "C:\test.mdb" '<----------------------------------------- INPUT
Table_Name = "New_Table" '<------------------------------------------------- INPUT
'RUN THE SQL TOOL                                                            =)
Call Delete_DB_Table(DB_Location_Name, Table_Name)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////

End Sub







Sub temporary_sub5()

'PREFORM SQL CODE TO GENERATE ARRAY WITH OUT TITLES
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim DB_Location_Name As String ' Full path and file name of database
Dim Table_Name As String ' Name of db table to delete
Dim SQL_Text As String
Dim My_Array As Variant

Table_Name = "New_Table" '<------------------------------------------------- INPUT
DB_Location_Name = "C:\test.mdb" '<----------------------------------------- INPUT
SQL_Text = "SELECT * FROM " & Table_Name & " WHERE [Part_type]='Seal'"  '<-- INPUT
'RUN THE SQL TOOL                                                            =)
My_Array = SQL_to_Array_wo_Titles(DB_Location_Name, SQL_Text) 'FORMAT: Array(Column,Row) top Left starting at (0,0)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////

End Sub







Sub temporary_sub6()

'PREFORM SQL CODE TO GENERATE ARRAY WITH TITLES
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim DB_Location_Name As String ' Full path and file name of database
Dim Table_Name As String ' Name of db table to delete
Dim SQL_Text As String
Dim My_Array As Variant

Table_Name = "New_Table" '<------------------------------------------------- INPUT
DB_Location_Name = "C:\test.mdb" '<----------------------------------------- INPUT
SQL_Text = "SELECT * FROM " & Table_Name & " WHERE [Part_type]='Seal'"  '<-- INPUT
'RUN THE SQL TOOL                                                            =)
My_Array = SQL_to_Array_w_Titles(DB_Location_Name, SQL_Text) 'FORMAT: Array(Column,Row) starting at (0,0)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////

End Sub







Sub temporary_sub7()

'PREFORM SQL CODE AND PASTE INTO RANGE
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim DB_Location_Name As String ' Full path and file name of database
Dim Table_Name As String ' Name of db table to delete
Dim SQL_Text As String
Dim Target_Range As Range
Dim With_Titles As Boolean

Table_Name = "New_Table" '<------------------------------------------------- INPUT
DB_Location_Name = "C:\test.mdb"  '<---------------------------------------- INPUT
SQL_Text = "SELECT * FROM " & Table_Name & " WHERE [Part_type]='Seal'"  '<-- INPUT
Target_Sheet = "Output"  '<------------------------------------------------- INPUT
With_Titles = True '<------------------------------------------------------- INPUT

'RUN THE SQL TOOL                                                            =)
Set Target_Range = ThisWorkbook.Sheets(Target_Sheet).Cells(2, 2)

Call SQL_to_Range(DB_Location_Name, SQL_Text, Target_Range, With_Titles)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////

End Sub





Sub temporary_sub8()

'CREATE A TABLE IN THE DB FROM ARRAY (with first record titles)
' /////////////////////////////////////////////////////////////////////////////////////
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
' \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Dim i As Integer ' General counter
Dim New_Table_Name As String ' Name of table in database, no spaces
Dim DB_Location_Name As String ' Full path and file name of database
ReDim Data_Array(1 To 3, 1 To 100) As String

'A loop in code is best to create an array, but for simplicity we will use this example
'ARRAY FORMAT: Array(Column,Row) top Left starting at (0,0)
'You MUST create an array that top row contains the title for every column
Data_Array(1, 1) = "Name" ' COLUMN TITLE
Data_Array(1, 2) = "Mary"
Data_Array(1, 3) = "Joe"
Data_Array(1, 4) = "Bob"

Data_Array(2, 1) = "Eye_Color" ' COLUMN TITLE 'NOTE, no spaces for titles
Data_Array(2, 2) = "Blue"
Data_Array(2, 3) = "Brown"
Data_Array(2, 4) = "Hazel"


Data_Array(3, 1) = "Height" ' COLUMN TITLE
Data_Array(3, 2) = "6'2"
Data_Array(3, 3) = "5'6"
Data_Array(3, 4) = "4'9"


'Resize the array accordingly
ReDim Preserve Data_Array(1 To 3, 1 To 4) ' You can only change the range of the last array dimension


DB_Location_Name = "C:\test.mdb" '<----------------------------------------- INPUT
New_Table_Name = "New_Table" '<--------------------------------------------- INPUT
'RUN THE SQL TOOL                                                            =)
Call Array_to_DB_table(DB_Location_Name, New_Table_Name, Data_Array)
'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'/////////////////////////////////////////////////////////////////////////////////////

End Sub
 
Upvote 0

Forum statistics

Threads
1,226,837
Messages
6,193,257
Members
453,786
Latest member
ALMALV

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top