How to CREATE TABLE using sql/VBA in excel with ADO - sql

I'm trying to erase table content and replace it with new content in an excel sheet.
The code doesn't raise any errors however everytime I run it, it inserts some blanck cells before the source table.
The 'base.xlsx' table sheet looks like this :
If target.xlsx is void before running the code I get what I want however if I run it again I get this :
Here is the code :
Sub SQLQUERY()
Dim Cn As ADODB.Connection
Dim QUERY_SQL As String
Dim ExcelCn As ADODB.Connection
SourcePath = "C:\Path\to\base.xlsx"
TargetPath = "C:\Path\to\target.xlsx"
CHAINE_HDR = "[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] "
Set Cn = New ADODB.Connection
STRCONNECTION = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source='" & SourcePath & "';" & _
"Mode=Read;" & _
"Extended Properties=""Excel 12.0;"";"
Colonnes = "[Col#1], Col2"
QUERY_SQL = _
"SELECT " & Colonnes & " FROM [base$] " & _
"IN '" & SourcePath & "' " & CHAINE_HDR
MsgBox (QUERY_SQL)
Cn.Open STRCONNECTION
Set ExcelCn = New ADODB.Connection
ExcelCn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & TargetPath & ";" & _
"Extended Properties=""Excel 12.0;HDR=YES;"""
ExcelCn.Execute "DROP TABLE [sheet$]"
ExcelCn.Execute "CREATE TABLE [sheet$] ([C1] Float, [C2] Float, [C3] Float)"
Cn.Execute "INSERT INTO [sheet$] (C1, C3) IN '" & TargetPath & "' 'Excel 12.0;' " & QUERY_SQL
'--- Fermeture connexion ---
Cn.Close
ExcelCn.Close
End Sub

After some research I discovered what's going on with the code. When Drop Table is executed Excel keep the "active range" and thus INSERT INTO will insert data after the active range.
To counter this we need to specify a range with the table name :
ExcelCn.Execute "DROP TABLE [sheet$]"
ExcelCn.Execute "CREATE TABLE [sheet$] ([C1] Float, [C2] Float, [C3] Float)"
Cn.Execute "INSERT INTO [sheet$A1:ZZ1] (C1, C3) IN '" & TargetPath & "' 'Excel 12.0;' " & QUERY_SQL
'--- Fermeture connexion ---
Note the [sheet$A1:ZZ1] in the sql statement.

Related

Issue Referencing Column in VBA SQL Query

I have an excel spreadsheet that I'm trying to perform SQL queries on. I get "no value given for one or more required parameters", so I think it's a problem with my query. I can do a query like "SELECT * FROM [Employee$A2:A4]", but when I reference a particular column using the name (i.e. name, title...etc, or even using the generic column reference like F1) I get "No value given for one or more required parameters."
Here's my code:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT Employee FROM [Employee$] AS e WHERE e.Skill_Title = " & """" & skillTitle & """" & " AND e.Branch = " & """" & branchTitle & """" & " AND e.Skill_Prof = 5"
rs.Open strSQL, cn
MsgBox (rs.GetString)
Any ideas what might be going on?
Try applying the following example.
Tell me if the problem persists and the inputs you're using.
I have this on Employee sheet:
Created "MyQuery" subprocess as follows (as you can see, this is a replica of your code, with some little differences):
Sub MyQuery(ByVal skillTitle As String, _
ByVal branchTitle As String, _
ByVal skillProf As Integer)
Dim Cn As ADODB.Connection
Dim Rs As ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strFile & ";" & _
"Extended Properties=""Excel 12.0;" & _
"HDR=Yes;" & _
"IMEX=1"";"
Set Cn = CreateObject("ADODB.Connection")
Set Rs = CreateObject("ADODB.Recordset")
Cn.Open strCon
strSQL = _
"SELECT Employee " & _
"FROM [Employee$] AS e " & _
"WHERE e.Skill_Title = '" & skillTitle & "' AND " & _
"e.Branch = '" & branchTitle & "' AND " & _
"e.Skill_Prof = " & CStr(skillProf)
Rs.Open strSQL, Cn
MsgBox (Rs.GetString)
'Do not forget closing your connection'
Rs.Close
Cn.Close
End Sub
Made a quick test:
Sub test()
'Try running this'
Call MyQuery("FOUR", "Y", 5)
End Sub
Result:
Have you named the columns? I wasn't sure from your code example whether you had named the columns or were assuming the column header would suffice for a reference. A "named" column is not the same as using a column header. To access the column by name try assigning a name to the column first.
From: How to give a name to the columns in Excel
Click the letter of the column you want to change and then click the "Formulas" tab.
Click "Define Name" in the Defined Names group in the Ribbon to open the New Name window.
Enter the new name of the column in the Name text box.

Updating SQL Server table with data from a table in different database using Excel VBA

I am trying to create Excel VBA to update table SQL Server. This allows my users to perform the update themselves. (using VBA for the first time)
I am getting a runtime error when I run the VBA code.
Here is my code:
Sub DataUpdateSQLServer()
Dim cnLogs As New ADODB.Connection
Dim rsHeaders As New ADODB.Recordset
Dim rsData As New ADODB.Recordset
Dim uSQL As String
strConn = "PROVIDER=SQLOLEDB;"
strConn = strConn & "DATA SOURCE=abc-dwh ;INITIAL CATALOG=DWH_DEV;"
strConn = strConn & " INTEGRATED SECURITY=sspi;"
strConn = strConn & "User ID= ARGUSGROUP\user;"
strConn = strConn & "Password = Password;"
strConn = strConn & "Trusted_Connection=No"
cnLogs.Open strConn
uSQL = "INSERT INTO DWH_DEV.DBO.GI_PRODUCTION_REPORT_CATALOG (Name, Path, CreationDate) " _
& "select C1.Name, C1.Path, C1.CreationDate " _
& "from ReportServer.dbo.Catalog C1 " _
& "LEFT JOIN DWH_DEV.DBO.GI_PRODUCTION_REPORT_CATALOG C2 " _
& "ON C1.PATH = C2.Path COLLATE SQL_Latin1_General_CP1_CI_AS " _
& "WHERE (C1.Path LIKE '/Reports/Production/Customer Service%' " _
& "OR C1.Path LIKE '/Reports/Production/Client Solutions%' " _
& "OR C1.Path LIKE '/Reports/Production/Finance/Group Insurance%' " _
& "OR C1.Path LIKE '/Reports/Production/Group Insurance%' " _
& "OR C1.Path LIKE '/Reports/Production/OTH%') AND C2.PATH IS NULL "
cnLogs.Execute uSQL
End Sub
Please help me. TIA.
I was able to get what I need from this link here:
http://www.vbforums.com/showthread.php?552665-Database-How-do-I-use-an-ADO-Command-object
The changes I made:
1.Added spaces to end of each line of SQL code.
2.Used ADO Command Object as discussed in the link above.
Here is my final code:
Sub DatafromSQLServer()
Dim cnLogs As New ADODB.Connection
Dim rsHeaders As New ADODB.Recordset
Dim rsData As New ADODB.Recordset
Dim uSQL As String
Dim l_counter As Long: l_counter = 0
Dim strConn As String
Sheets(1).UsedRange.Clear
strConn = "PROVIDER=SQLOLEDB;"
strConn = strConn & "DATA SOURCE=abc-dwh ;INITIAL CATALOG=DWH_DEV;"
strConn = strConn & " INTEGRATED SECURITY=sspi;"
strConn = strConn & "User ID= ARGUSGROUP\user;"
strConn = strConn & "Password = Password"
strConn = strConn & "Trusted_Connection=No"
cnLogs.Open strConn
CSQL = "INSERT INTO DWH_DEV.DBO.GI_PRODUCTION_REPORT_CATALOG (Name, Path, CreationDate) " _
& "select C1.Name, C1.Path, C1.CreationDate " _
& "from ReportServer.dbo.Catalog C1 " _
& "LEFT JOIN DWH_DEV.DBO.GI_PRODUCTION_REPORT_CATALOG C2 " _
& "ON C1.PATH = C2.Path COLLATE SQL_Latin1_General_CP1_CI_AS " _
& "WHERE (C1.Path LIKE '/Reports/Production/Customer Service%' " _
& "OR C1.Path LIKE '/Reports/Production/Solutions%' " _
& "OR C1.Path LIKE '/Reports/Production/Finance/Insurance%' " _
& "OR C1.Path LIKE '/Reports/Production/Insurance%' " _
& "OR C1.Path LIKE '/Reports/Production/OTH%') AND C2.PATH IS NULL "
Dim objCommand As ADODB.Command
Set objCommand = New ADODB.Command
With objCommand
.ActiveConnection = cnLogs 'replace this with your Connection object
.CommandType = adCmdText
.CommandText = CSQL 'replace this with your SQL statement
.Prepared = True
objCommand.Execute , , adExecuteNoRecords
End With
Set objCommand = Nothing
End Sub

Use Offset with Excel SQL query

I'm working on an excel file to collect information from others closed Excel files
The provider is Microsoft.ACE.OLEDB.12.0 and everything works fine (almost).
In order to have updateable query, I used the command HDR = no in order to have column name like F1, F2, F3... and I retrieve the name after (see the code below, code from Stack Overflow).
However, with the command Union All, I also retrieved the headers as data, if I collect data from 5 files, I'll get 5 headers.
So I'm looking for a solution to retrieve header with command HDR = NO on Excel SQL query (start at line 2 in each file).
I tried OFFSET command in SQL query but I get an error message.
I also tried to get the row number in the original file but I didn't find the command.
Do you have any idea to help me on this issue?
Many thanks in advance,
BR
Code for information:
Option Explicit
Sub SqlUnionTest()
Dim strConnection As String
Dim strQuery As String
Dim objConnection As Object
Dim objRecordSet As Object
strConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"User ID=Admin;" & _
"Data Source='" & ThisWorkbook.FullName & "';" & _
"Mode=Read;" & _
"Extended Properties=""Excel 12.0 Macro;"";"
strQuery = _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Source1.xlsx' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=NO;'] " & _
"UNION " & _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Source2.xlsx' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=NO;'] " & _
"UNION " & _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Source3.xlsx' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=NO;'] " & _
"ORDER BY ContactName;"
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open strConnection
Set objRecordSet = objConnection.Execute(strQuery)
RecordSetToWorksheet Sheets(1), objRecordSet
objConnection.Close
End Sub
Sub RecordSetToWorksheet(objSheet As Worksheet, objRecordSet As Object)
Dim i As Long
With objSheet
.Cells.Delete
For i = 1 To objRecordSet.Fields.Count
.Cells(1, i).Value = objRecordSet.Fields(i - 1).Name
Next
.Cells(2, 1).CopyFromRecordset objRecordSet
.Cells.Columns.AutoFit
End With
End Sub
You can specify the starting and ending row while querying the excel file. So Instead of -
SELECT * FROM [Sheet1$]
Use This -
SELECT * FROM [Sheet1$A2:end]
A2 - it will start reading from 2nd row.
end - will read until the sheet has data. So suppose, if you want to only some rows from SHEET1. Use this -
SELECT * FROM [Sheet1$A2:A10]

MS EXCEL to MS ACCESS .accdb Database from VBA SQL Syntax error

I am completely stuck and pulling out my hair on this one..
From Excel VBA I have two sets of code:
1- To Create a table is MS Access via a SQL statement
2- Populated newly created table with a For loop, also using SQL
The first set of code works perfectly, so I know that my connection string is working properly.
Here is the first set:
Sub Create_Table()
'Add Reference to Microsoft ActiveX Data Objects 2.x Library
Dim strConnectString As String
Dim objConnection As ADODB.Connection
Dim strDbPath As String
Dim strTblName As String
Dim wCL As Worksheet
Dim wCD As Worksheet
Set wCL = Worksheets("Contract List")
Set wCD = Worksheets("Contract Data")
'Set database name and DB connection string--------
strDbPath = ThisWorkbook.Path & "\SpreadPrices.accdb"
'==================================================
strTblName = wCL.Range("TableName").Value
strConnectString = "Provider = Microsoft.ACE.OLEDB.12.0; data source=" & strDbPath & ";"
'Connect Database; insert a new table
Set objConnection = New ADODB.Connection
On Error Resume Next
With objConnection
.Open strConnectString
.Execute "CREATE TABLE " & strTblName & " (" & _
"[cDate] text(150), " & _
"[Open] text(150), " & _
"[High] text(150), " & _
"[Low] text(150), " & _
"[Last] text(150), " & _
"[cChange] text(150), " & _
"[Settle] text(150), " & _
"[cVolume] text(150), " & _
"[OpenInterest] text(150))"
End With
Set objConnection = Nothing
End Sub
Mentioned before that code works perfectly. The bug is on the following set of code used to populate the table.
Here it is:
Sub InsertSQL()
'Add Reference to Microsoft ActiveX Data Objects 2.x Library
Dim strConnectString As String
Dim objConnection As ADODB.Connection
Dim strDbPath As String
Dim strTblName As String
Dim lngRow As Long
Dim strSQL As String
Dim wCL As Worksheet
Dim wCD As Worksheet
Set wCL = Worksheets("Contract List")
Set wCD = Worksheets("Contract Data")
'Set database name and DB connection string--------
strDbPath = ThisWorkbook.Path & "\SpreadPrices.accdb"
'==================================================
strTblName = wCL.Range("TableName").Value
strConnectString = "Provider = Microsoft.ACE.OLEDB.12.0; data source=" & strDbPath & ";"
'Connect Database; insert a new table
Set objConnection = New ADODB.Connection
'On Error Resume Next
With objConnection
.Open strConnectString
For lngRow = 2 To Range("NumberRows").Value
strSQL = "INSERT INTO " & strTblName & " (" & _
"cDate, Open, High, Low, Last, cChange, Settle, cVolume, OpenInterest)" & _
" VALUES ('" & _
wCD.Cells(lngRow, 1) & "' , '" & _
wCD.Cells(lngRow, 2) & "' , '" & _
wCD.Cells(lngRow, 3) & "' , '" & _
wCD.Cells(lngRow, 4) & "' , '" & _
wCD.Cells(lngRow, 5) & "' , '" & _
wCD.Cells(lngRow, 6) & "' , '" & _
wCD.Cells(lngRow, 7) & "' , '" & _
wCD.Cells(lngRow, 8) & "' , '" & _
wCD.Cells(lngRow, 9) & "')"
wCL.Range("A1").Value = strSQL
.Execute strSQL
Next lngRow
End With
Set objConnection = Nothing
End Sub
The error I receive is:
Run-time error, Syntax error in INSERT INTO statement.
Ok, so at first thought I think there must be a error in my SQL string. So I take the exact SQL string and toss it into Access Query Builder and run the SQL command and it imports into the table just fine.
What am I missing?
The problem may be due to field names. There is a function named CDate. Open and Last are both Jet reserved words. See Problem names and reserved words in Access.
Enclose those problem field names in square brackets to avoid confusing the database engine:
"[cDate], [Open], High, Low, [Last], cChange, Settle, cVolume, OpenInterest)"
The brackets may be enough to get your INSERT working. However consider renaming the fields if possible.
That linked page also mentions Allen Browne's Database Issue Checker Utility. You can download that utility and use it to examine your database for other problem names. It can also alert you to other issues which may not affect the current INSERT problem, but could cause trouble in other situations.

Create a SQL Table from Excel VBA

The problem is that I cannot get the table name that was entered into the variable, "tblName", to be used instead I get a correctly named database with a table named "tblName".
Is there some way to pick up the name in "tblName" or some way to change the name once it is created with a name th user enters?
Private Sub CreateDatabaseFromExcel()
Dim dbConnectStr As String
Dim Catalog As Object
Dim cnt As ADODB.Connection
Dim dbPath As String
Dim tblName As String
'Set database name in the Excel Sheet
dbPath = ActiveSheet.Range("B1").Value 'Database Name
tblName = ActiveSheet.Range("B2").Value 'Table Name
dbConnectStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ";"
'Create new database using name entered in Excel Cell ("B1")
Set Catalog = CreateObject("ADOX.Catalog")
Catalog.Create dbConnectStr
Set Catalog = Nothing
'Connect to database and insert a new table
Set cnt = New ADODB.Connection
With cnt
.Open dbConnectStr
.Execute "CREATE TABLE tblName ([BankName] text(50) WITH Compression, " & _
"[RTNumber] text(9) WITH Compression, " & _
"[AccountNumber] text(10) WITH Compression, " & _
"[Address] text(150) WITH Compression, " & _
"[City] text(50) WITH Compression, " & _
"[ProvinceState] text(2) WITH Compression, " & _
"[Postal] text(6) WITH Compression, " & _
"[AccountAmount] decimal(6))"
End With
Set cnt = Nothing
End Sub
Change this line:
.Execute "CREATE TABLE tblName ([BankName] text(50) WITH Compression, " & _
To this:
.Execute "CREATE TABLE " & tblName & " ([BankName] text(50) WITH Compression, " & _