UNPIVOT columns using SQL query - sql

I am pulling another workbook containing a table that has Columns like ItemCreationDate, and most columns (total 28 such columns) that begin with the word "Global" in them. i want to
pull these "Global" columns (including ItemCreationDate) into an SQL recordset,
add a new Column called Old/New and then
UNPIVOT them i.e. Stack them up one above the other and
in the next column, list their Column items along with their Counts.
Their Counts are derived based on the ItemCreationDate where any date <2015 is OLD & >=2015 is NEW
Final Output should be as shown in Output sheet.
i have attached a Sample.xlsx file where i have shown how i have to arrive at the Output tab starting from the Data sheet. This Data sheet is actually the input that i want to pull into a recordset and spit out the table as shown in the Output sheet. I don't want to create Pivot table as its cumbersome and the data is quite a lot, and i want an alternative SQL approach, wherein i can quickly aggregate the data and insert it into sheet in one go.
i am not using SQL Server, so cannot use the UNPIVOT command or Dynamic SQL to loop thru all the "Global" columns.
Basically i want to form a correct SQL string something like....
Dim arrSQL as variant
......
......
RS.Filter="Like Global*"
......
arrSQL = JOIN(RS.Fields, vbCr)
strSQL = "SELECT [arrSQL], IIF(YEAR([ITEM CREATION DATE])>=YEAR(DATE())-1,""NEW"",""OLD"") AS [New/Old] from [Data$] GROUP BY...."
strSQL = strSQL & " UNION ALL " & vbcr & _
strSQL = strSQL & " ......
Now, run SQL on same recordset to reduce the columns and get required data format....
i know the above is not quite correct, but something on those lines so that i can get the correct output as show in the Output tab.
can anyone help quickly?
Edits for #a_horse_with_no_name :
see the screenshots of the sample file:
Data sheet:
this is actually a table from an input workbook that i want to pull in a Recordset. See the various "Global" column headings and their items that i want to unpivot.
This are the 2 intermediate sheets "New" & "Old" i have to create everytime (that i want to get rid of actually). any items found in 2015 or later are put in New, whereas rest are put in Old.
JFYI, the formulae that are manually used in Output columns are :
C column (New):
=COUNTIF(INDEX(New!$A:$D,0,MATCH($A2,New!$1:$1,0)),Output!$B2)
D Column (Old):
=COUNTIF(INDEX(Old!$A:$D,0,MATCH($A2,Old!$1:$1,0)),Output!$B2)
E Column (% New):
=Output!C2/SUM(C$2:C$6)
F Column (% Old):
=Output!D2/SUM(D$2:D$6)
G Column (Index):
=IF(AND(E2<=0,F2<=0),0,IF(AND(E2>0,F2>0),E2/F2,1))
Hope this helps.

Indeed, you can run SQL queries in MS Excel using the Jet/ACE SQL Engine (a Windows .dll file) which is the very data store that MS Access is connected to by default. And as such, this technology equipped on all PCs is not restricted to any one Office/Windows program.
Consider the following Excel VBA macro (if using Excel on PC) that connects to ACE via ADO running a union of three aggregate SQL queries (GLOBAL VIT/CALC, GLOBAL FLAVOURS, GLOBAL FLAVOUR GROUP) and conditional New and Old counts/percentages. The latter percentage column pair required subqueries.
For proper setup, do the following:
Make sure Item Creation Date is in MM-DD-YYYY (US-based) or DD-MM-YYYY (non-US based) date formats which is not how above screenshot or file has date field currently formatted.
Sub FormatDates()
For i = 2 To 2083
Range("A" & i) = CDate(Range("A" & i))
Next i
End Sub
Run macro in a different workbook than the one holding the data. Below assumes data workbook holds source information in worksheet named Data.
In query-running workbook, create a blank worksheet named RESULTS which will be populated with query output including column headers.
VBA Script (two connections available Driver (commented out) and Provider versions)
Option Explicit
Sub RunSQL()
Dim cols As Object, datawbk As Workbook, datawks As Worksheet
Dim lastcol As Integer, i As Integer, j As Variant, output As Variant
Set cols = CreateObject("Scripting.Dictionary")
Set datawbk = Workbooks.Open("C:\Path\To\Data\Workbook.xlsx;")
Set datawks = datawbk.Worksheets("Data")
lastcol = datawks.Cells(7, datawks.Columns.Count).End(xlToLeft).Column
For i = 2 To lastcol
cols.Add CStr(i - 1), datawks.Cells(1, i).Value
Next i
datawbk.Close False
Set datawks = Nothing
Set datawbk = Nothing
output = DataCapture(cols)
End Sub
Function DataCapture(datacols As Object)
On Error GoTo ErrHandle
Dim conn As Object, rst As Object
Dim strConnection As String
Dim classSQL As String, itemSQL As String, grpSQL As String, strSQL As String
Dim i As Integer, fld As Object, d As Variant, lastrow As Integer
Set conn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
' Hard code database location and name '
' strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
' & "DBQ=C:\Path\To\Data\Workbook.xlsx;"
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
& "Data Source='C:\Path\To\Data\Workbook.xlsx;" _
& "Extended Properties=""Excel 12.0 XML;HDR=YES IMEX=1;"";"
' OPEN DB CONNECTION '
conn.Open strConnection
For Each d In datacols.keys
strSQL = " SELECT '" & datacols(d) & "' AS [COLUMN], [Data$].[" & datacols(d) & "] AS ITEMS," _
& " SUM(IIF(Year([Item Creation Date]) >= Year(Date()) - 1, 1, 0)) AS NEW," _
& " " _
& " SUM(IIF(Year([Item Creation Date]) < Year(Date()) - 1, 1, 0)) AS OLD," _
& " " _
& " ROUND(SUM(IIF(Year([Item Creation Date]) >= Year(Date()) - 1, 1, 0)) / " _
& " (SELECT Count(*) FROM [Data$] AS sub" _
& " WHERE Year(sub.[Item Creation Date]) >= Year(Date()) - 1),2) AS NEWPCT," _
& " " _
& " ROUND(SUM(IIF(Year([Item Creation Date]) < Year(Date()) - 1, 1, 0)) / " _
& " (SELECT Count(*) FROM [Data$] AS sub" _
& " WHERE Year(sub.[Item Creation Date]) < Year(Date()) - 1),2) AS OLDPCT" _
& " FROM [Data$]" _
& " GROUP BY [Data$].[" & datacols(d) & "]"
' OPEN RECORDSET '
rst.Open strSQL, conn
' COLUMN HEADERS '
If d = 1 Then
i = 0
Worksheets("RESULTS").Range("A1").Activate
For Each fld In rst.Fields
ActiveCell.Offset(0, i) = fld.Name
i = i + 1
Next fld
End If
' DATA ROWS '
lastrow = Worksheets("RESULTS").Cells(Worksheets("RESULTS").Rows.Count, "A").End(xlUp).Row
Worksheets("RESULTS").Range("A" & lastrow + 1).CopyFromRecordset rst
rst.Close
Next d
conn.Close
MsgBox "Successfully processed SQL query!", vbInformation
Exit Function
ErrHandle:
MsgBox Err.Number & " - " & Err.Description, vbCritical
Exit Function
End Function
Output

Related

Use VBA to import data from SSMS joined table into an Excel file

I am trying to import some fields from two tables that need to be joined from SSMS. The importation process is through VBA. When importing from a singular table, my query ran fine but when I tried introducing a joined format, I received the error Run-time error -2147217900 (80040e14) Incorrect Syntax near 'dd' This piece of code is where the error gets thrown:
'The line item below is what gets highlighted and throws the error message
rsData.Open strQuery, objConn
Sub GetData_Using_VERSION_ID()
Dim strConnectionString As String, strQuery As String, strMessage As String
Dim objConn As ADODB.Connection
Dim rsData As New ADODB.Recordset
Dim varArrayReader As Variant
Dim tot_rows As Long
Dim intLBoundColumn As Long, intUBoundColumn As Long ' this variable is meant to hold the lower and upper indexes of the 1st dimension of the Array (columns)
Dim intLBoundRow As Long, intUBoundRow As Long ' this variable is meant to hold the lower and upper indexes of the 2nd dimension of the Array (rows)
Dim intLBoundColumn2 As Long, intUBoundColumn2 As Long ' this variable is meant to hold the lower and upper indexes of the 1st dimension of the Array (columns)
Dim intLBoundRow2 As Long, intUBoundRow2 As Long ' this variable is meant to hold the lower and upper indexes of the 2nd dimension of the Array (rows)
Dim intLBoundColumn3 As Long, intUBoundColumn3 As Long ' this variable is meant to hold the lower and upper indexes of the 1st dimension of the Array (columns)
Dim intLBoundRow3 As Long, intUBoundRow3 As Long ' this variable is meant to hold the lower and upper indexes of the 2nd dimension of the Array (rows)
Dim intLBoundColumn4 As Long, intUBoundColumn4 As Long ' this variable is meant to hold the lower and upper indexes of the 1st dimension of the Array (columns)
Dim intLBoundRow4 As Long, intUBoundRow4 As Long ' this variable is meant to hold the lower and upper indexes of the 2nd dimension of the Array (rows)
Dim i As Long, j As Long
Dim found As Integer
Dim VId As String
Dim ews As Excel.Worksheet
Dim sws As Excel.Worksheet
Dim lws As Excel.Worksheet
'Variable to determine if App version is found for ny_id lookup
found = 0
VId = Cells(1, 3)
Set ews = Worksheets("Employer_Data")
Set sws = Worksheets("Student_Data")
Set lws = Worksheets("Loan_Data")
'Determine if Ny_id has been found or not to set the initial total rows
'tot_rows is the starting point for the inserting of the headers and data beneath them
If Cells(2, 1) = "" Or Cells(1, 1) = "" Then
tot_rows = 3
Else
tot_rows = Range("A2").End(xlDown).Row + 3
End If
'See if valid app version id input for lookup
If VId = "" Or Not IsNumeric(VId) Then
Rows(tot_rows - 1 & ":" & Rows.Count).ClearContents
ews.Rows(tot_rows - 1 & ":" & Rows.Count).ClearContents
sws.Rows(tot_rows - 1 & ":" & Rows.Count).ClearContents
lws.Rows(tot_rows - 1 & ":" & Rows.Count).ClearContents
Cells(tot_rows - 1, 1).Value = "Bad Application_Version_ID Entered"
ews.Cells(tot_rows - 1, 1).Value = "No Application_Version_ID Entered"
sws.Cells(tot_rows - 1, 1).Value = "No Application_Version_ID Entered"
lws.Cells(tot_rows - 1, 1).Value = "No Application_Version_ID Entered"
Else
'Connection string for our Dev Database
strConnectionString = "Provider = SQLOLEDB;" _
& "Data Source=NAME REMOVED FOR DATA INTEGRITY;" _
& "Initial Catalog=NAME REMOVED FOR DATA INTEGRITY;" _
& "User ID=NAME REMOVED FOR DATA INTEGRITY;" _
& "Password=NAME REMOVED FOR DATA INTEGRITY;"
'***THIS CODE WORKS BY PULLING FIELDS FROM A SINGULAR TABLE SOURCE BUT I NEED TO PULL FIELDS FROM A JOINED TABLE
'Add/Update/Remove Fields Here
'NY_CALCULATION SQL Statement to pull data
' strQuery = ""
' strQuery = strQuery & "SELECT NY_ID, APPLICATION_VERSION_ID, grad_year, year, month, calc_year, marital_status, number_dependents, " _
' & "annual_gross_salary , qual_income, month_part_cont, monthly_payment_non_law, monthly_payment_law, month_lrap_benefit, spouse_annual_gross_salary, " _
' & "spouse_monthly_payment_ug , orig_principle_law, adjusted_orig_principle_law " _
' & "FROM [dbo].[NY_CALCULATION]" & " WHERE APPLICATION_VERSION_ID in (" & VId & ") order by application_version_id, month"
'*************************************************************
'THIS IS THE QUERY STRUCTURE THAT I NEED TO USE TO PULL THE NECESSARY FIELDS FROM SSMS INTO AN EXCEL FILE, HOWEVER AS MENTIONED I RECEIVE AN ERROR. I ASSUME THAT MAYBE I DIDN'T STRUCTURE THE QUERY PROPERLY?
strQuery = ""
strQuery = strQuery & "SELECT ah.NY_ID, ah.NEW_APPLICATION_ID, dd.GRAD_YEAR, dd.FIRST_NAME, dd.LAST_NAME, dd.MARITAL_STATUS, dd.NUMBER_DEPENDENTS, " _
& "dd.LRAP_PROGRAM, dd.CREATED_TIME " _
& "FROM [dbo].[NY_APPLICATION_HISTORY] ah" _
& "LEFT JOIN [dbo].[NY_DEMOGRAPHIC_DATA] dd" _
& "ON dd.APPLICATION_VERSION_ID = ah.NEW_APPLICATION_ID" _
& " WHERE APPLICATION_VERSION_ID in (" & VId & ")" _
& "ORDER BY ah.NEW_APPLICATION_ID"
'Execute SQL statement
Set objConn = New ADODB.Connection
objConn.Open strConnectionString
Set rsData = New ADODB.Recordset
'The line item below is what gets highlighted and throws the error message
rsData.Open strQuery, objConn
'Check to see if we were able to find data with select statement
If rsData.EOF Then
Cells(tot_rows - 1, 2).Value = "No Calculation Data found for that Application_Version_ID"
Else

Reading Excel file with SQL returns null due to empty column

I am attempting to read in an Excel File from a third party but it falls over and returns null due to empty column.
The file has 50 columns, a blank column and a further 48 columns. I only want the first 50 columns. If I delete or populate the empty column in Excel it works but I need to read 50+ files one after the other, regularly, so opening/deleting/saving isn't an option.
Function read_excel_file(StrPath, StrFile, ByRef TotalFileArray() As Variant)
Dim ReadFileArray() As Variant
Dim connectionString As String
connectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=""" & StrPath & StrFile & """;" & _
"Extended Properties=""Excel 12.0;HDR=Yes;"""
'This assumes the Excel file contains column headers -- HDR=Yes
'Routine to get unknown sheet name
Set conn = CreateObject("ADODB.Connection")
conn.connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=""" & StrPath & StrFile & """;" & _
"Extended Properties=""Excel 12.0;HDR=No"""
conn.Open
Set bs = conn.OpenSchema(20) ' 20 = adSchemaTables
Do Until bs.EOF = True
'Debug.Print bs.Fields!Table_Name.Value
SheetName = bs.Fields!Table_Name.Value
bs.MoveNext
Loop
bs.Close: conn.Close
Set bs = Nothing
Set conn = Nothing
Dim sql As String
'sql = "SELECT Meter Id, Date, 00:30, 01:00, 01:30, 02:00, 02:30, 03:00, 03:30, 04:00, 04:30, 05:00, 05:30, 06:00, 06:30, 07:00, 07:30, 08:00, 08:30, 09:00, 09:30, 10:00, 10:30, 11:00, 11:30, 12:00, 12:30, 13:00, 13:30, 14:00, 14:30, 15:00, 15:30, 16:00, 16:30, 17:00, 17:30, 18:00, 18:30, 19:00, 19:30, 20:00, 20:30, 21:00, 21:30, 22:00, 22:30, 23:00, 23:30, 24:00:00 FROM [" + SheetName + "]" '
sql = "SELECT * FROM [" + SheetName + "]" '
'Dim rs As Object 'New adodb.Recordset
'Set rs = CreateObject("ADODB.Connection")
Dim rs As New ADODB.Recordset
rs.Open sql, connectionString
ReadFileArray() = rs.GetRows 'Puts the data from the recordset into an array
rs.Close
Set rs = Nothing
I did try using specific requests for the columns I wanted but this still returned null. I attempted a single column but again returned null.
Is there a way around the empty column? Even if reading the file in a different way. (I nearly always read in csv files which are a breeze to get into an array and deal with.)
Picture of source data headers
Given that you have no choice but to work with the files in the format provided, the best approach/workaround (rather than manually opening/deleting/saving/closing the files individually) would appear to be to pre-process them using VBA to delete the offending column, before then running your query.
If Excel worksheet contains columns in first row and you specify HDR=Yes, then your first SQL statement would work if you properly enclosed the column names with brackets since they contain special characters like spaces and start with numbers.
' OPEN CONNECTION WITH HEADERS INDICATED
connectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=""" & StrPath & StrFile & """;" & _
"Extended Properties=""Excel 12.0;HDR=Yes;"""
conn.Open connectionString
' RUN SQL WITH COLUMNS SPECIFIED
sql = "SELECT [Meter Id], [Date]" _
& " , [00:30], [01:00], ..., [23:30], [24:00:00]" _
& " FROM [" + SheetName + "]"
rs.Open sql, connectionString
...
In fact, your original attempt should have raised an error in attempting to run. Also, the second SQL with SELECT * FROM should raise an error with empty column since one of the column names is zero length which is an invalid identifier. Therefore, you need to explicitly select columns.
After deeper review, it appears your time columns may be in Custom format as time values which really are formatted Excel decimal values. Hence, the SQL engine cannot find [00:30] column. To fix, convert time value columns into text format.
Consider below subroutine to automate the conversion with Text(). You can then call this VBA sub or function from other main method on each worksheet before any SQL query. Do note there is no such time value as 24:00:00 so this may be already in text format.
Sub Clean_Time_Columns()
Dim i As Integer, lastcol As Integer
Dim tmp_time As Variant
With ThisWorkbook.Worksheets("DATA")
For i = 3 To 49 ' LEAVE OUT 24:00:00
tmp_time = .Cells(1, i).Value
.Cells(1, i).NumberFormat = "#"
.Cells(1, i).Value = Application.WorksheetFunction.Text(tmp_time, "HH:MM")
Next i
End With
End Sub

Is it possible to create a table from another table in Excel using SQL like syntax?

I have a table in excel that has multiple lines per date. I'd like to create a new table that groups by date as well as a few other dimensions and sums net_revenue.
In sql it would be simple:
SELECT send_date,
week_day,
after_hours,
discount_type,
sum(net_revenue
FROM this_table
GROUP BY send_date,
week_day,
after_hours,
discount_type
Is there a simple way to do this in excel? At first I thought pivot tables but I don't want each additional dimension on a new row.
This is what my current table looks like:
Consider the following strictly GUI interface solution:
Copy all your grouping fields as is into a separate sheet.
Under Data tab of ribbon, click Remove Duplicates, selecting all columns.
In the final column, run SUMIFS formula to calculate net_revenue sum, pointing to values in you original sheet.
=SUMIFS(<net_revenue_column>,
<1stgroup_column_in_first_sheet>, <1stgroup_value_in_second_sheet>,
<2ndgroup_column_in_first_sheet>, <2ndgroup_value_in_second_sheet>,
<3rdgroup_column_in_first_sheet>, <3rdgroup_value_in_second_sheet>,
...
)
Alternatively, actually run SQL (if using Excel for Windows) using the JET/ACE SQL Engine (same engine of MS Access that can query Excel workbooks even CSV files). Below assumes your data begins in A1 with named columns. Adjust sheet name in FROM clause.
Sub RunSQL()
Dim oConn, rs As Object
Dim strConnection, strSQL As String
Dim i As Integer
Set oConn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
' CONNECTION STRING ON CURRENT WORKBOOK
strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
& "DBQ=" & ThisWorkbook.FullName & ";"
' OPEN DB CONNECTION
oConn.Open strConnection
strSQL = "SELECT send_date, " _
& " week_day, " _
& " after_hours, " _
& " discount_type, " _
& " sum(net_revenue) AS total_revenue " _
& " FROM [SheetName$] " _
& " GROUP BY send_date, " _
& " week_day, " _
& " after_hours, " _
& " discount_type "
' OPEN RECORDSET OF QUERY
rs.Open strSQL, oConn
' OUTPUT DATA TO EXCEL WORKSHEET (IN EMPTY TAB NAMED "RESULTS")
' HEADERS
For i = 0 To rs.Fields.Count - 1
ThisWorkbook.Worksheets("RESULTS").Cells(1, i) = rs.Fields(i).Name
Next i
' ROWS
ThisWorkbook.Worksheets("RESULTS").Range("A2").CopyFromRecordset rs
rs.Close: oConn.Close
Set rs = Nothing: Set oConn = Nothing
End Sub

VBA Copy Whole Column From SQL Recordset

I have a fixed data set of 6 rows being queried in SQL. I want to transfer the data in this query into Excel. My question is in two parts:
1 - Can I pull back multiple columns in one go or do I have to do it column by column? I have 17 columns and 6 rows. As this is transferred into my Excel template I'm looking to break this up into thirds so columns 1 to 7 go in one space 8 to 11 in another section and 12 to 17 in another section in Excel.
2 - When using my current code of:
Range("F2").Value = rst.Fields("ACCOUNT")
I only pull back a single row, is it possible to get the whole column (all 6 rows) or do I have to loop all 6 rows to get the full column?
Thanks in advance
Use .GetRows() method, it allows to set a number of records to retrieve, first record to begin, and single field name or ordinal position, or an array of field names or ordinal position numbers.
The below example shows how to get data from external Excel workbook into recordset, retrieve specified fields into array, and paste result array to the worksheet.
Option Explicit
Sub Test()
Dim sConnection As String
Dim sQuery As String
Dim oConnection As Object
Dim oRecordset As Object
Dim aData()
sConnection = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"User ID=Admin;" & _
"Data Source='" & ThisWorkbook.FullName & "';" & _
"Mode=Read;" & _
"Extended Properties=""Excel 12.0 Macro;"";"
sQuery = _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src1.xlsx' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
"WHERE Country='UK';"
Set oConnection = CreateObject("ADODB.Connection")
oConnection.Open sConnection
Set oRecordset = oConnection.Execute(sQuery)
oRecordset.MoveFirst
aData = oRecordset.GetRows(, , Array("CustomerID", "ContactName"))
With ThisWorkbook.Sheets(1)
.Cells.Delete
Output2DArray .Cells(1, 1), WorksheetFunction.Transpose(aData)
.Cells.EntireColumn.AutoFit
End With
oConnection.Close
End Sub
Sub Output2DArray(oDstRng As Range, aCells As Variant)
With oDstRng
.Parent.Select
With .Resize( _
UBound(aCells, 1) - LBound(aCells, 1) + 1, _
UBound(aCells, 2) - LBound(aCells, 2) + 1)
.NumberFormat = "#"
.Value = aCells
End With
End With
End Sub
Also there is Src1.xlsx workbook containing Customers as data source in the same folder as this workbook:
The resulting worksheet is as follows, you can see there are CustomerID and ContactName fields only:

SQL update query to add Excel Data to Access

I've been searching for a direct solution, but haven't found anything quite like what I'm attempting to do on this board. I have an Excel worksheet that has several non-contiguous lists of bonds for different companies (think 5 bonds for one company, 3 fully empty rows, then another list of 6 bonds for another company, 5 fully empty rows, etc. etc.).
I'm trying to write an SQL update query that will directly update an Access table in .accdb format. I have fields that have the same name as the column headers in Excel, with the same data.
I need to perform this logic: where range A1 & B1 & C1 are not blank, add a new record to the table that shows A1 & B1 & C1 as fields [Ticker], [Coupon], [Maturity]. Where those cells ARE blank, move to the next row.
Can someone help evaluate my code? I'm getting an error 3343 at the point where I specify "Set db".
My preliminary code is below (scraped together from what I could find online as far as interfacing with Excel and SQL commands):
Sub UpdateDatabase()
Dim x As Integer
Dim strSQL As String
Dim db As Database
Dim dbLocation As String
Dim objConnection As Object
Worksheets("Bonds Clean").Activate
Range("A6").Select
dbLocation = "c:\Folders\Workflow Tables.accdb"
Set objConnection = CreateObject("DAO.DBEngine.36")
Set db = objConnection.OpenDatabase(dbLocation)
For x = 1 To Range(Selection, Selection.End(xlDown)).Rows.Count
If Not (Selection.Value = "") Then
strSQL = "UPDATE tblBonds_Temp SET"
strSQL = strSQL & "Ticker =" & Chr(34) & Selection.Offset(0, 1).Value & Chr(34) & ","
strSQL = strSQL & "Coupon =" & Chr(34) & Selection.Offset(0, 2).Value & Chr(34) & ","
strSQL = strSQL & "Maturity =" & Chr(34) & Selection.Offset(0, 3).Value & Chr(34) & ";"
db.Execute strSQL
Else
End If
Selection.Offset(1, 0).Select
Next
End Sub
DAO.DBEngine.36 is for DAO 3.6 which is suitable for MDB format database files. However, your database is ACCDB format which means that DAO 3.6 won't work. You must use the newer DAO instead.
'Set objConnection = CreateObject("DAO.DBEngine.36")
Set objConnection = CreateObject("DAO.DBEngine.120")