azizrasul
Well-known Member
- Joined
- Jul 7, 2003
- Messages
- 1,304
- Office Version
- 365
- 2019
- 2016
- Platform
- Windows
I am trying to run some SQL statements within a MS Excel file that contains Excel tables.
When I try to run Sub Test(), I get an error on the conn.Open line i.e.
-2147467259: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Any idea where I am going wrong? The code was extracted from a YouTube video called 'Building Excel SQL Query Application Part 1 - Write SQL Statement in Excel to query Excel tables'
I am using Excel version 15.0.
When I try to run Sub Test(), I get an error on the conn.Open line i.e.
-2147467259: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Any idea where I am going wrong? The code was extracted from a YouTube video called 'Building Excel SQL Query Application Part 1 - Write SQL Statement in Excel to query Excel tables'
I am using Excel version 15.0.
Code:
Sub Test()
QueryExcel ("SELECT tblLicences.Field1 FROM tblLicences WHERE (((tblLicences.Field1)='" & MotherBoardSerialNumber() & "'));")
End Sub
Public Sub QueryExcel(ByVal SQL_Statement As String)
Dim conn As ADODB.Connection
Dim rst1 As ADODB.Recordset
Dim cmd As ADODB.Command
Dim sConnection As String, sSQL As String
Dim ws As Worksheet
Dim i As Integer, iCheck As Integer
Dim num_records As Long
On Error GoTo errHandle
sConnection = "Provider=Microsoft.ACE.OLEDB.15.0;Data Source=" & ActiveWorkbook.FullName & _
";Extended Properties=Excel 15.0;HDR=YES;IMEX=0;ReadOnly=False"""
Set conn = CreateObject("ADODB.Connection")
Set rst1 = CreateObject("ADODB.Recordset")
sSQL = UCase(SQL_Statement)
conn.Open
If Left(sSQL, 6) = "UPDATE" Or InStr(sSQL, "INSERT INTO") = 0 Then
conn.Execute sSQL, num_records
MsgBox num_records & " records affected.", vbInformation
Else
rst1.Open sSQL, conn, adOpenDynamic, adLockOptimistic
Set ws = Worksheets.Add
With ws
.Move , ThisWorkbook.Worksheets(Sheets.Count)
.Range("A2").CopyFromRecordset rst1
For i = 0 To rst1.Fields.Count - 1
.Cells(1, i + 1) = rst1.Fields(i).Name
Next
End With
End If
Door:
If rst1.State <> 0 Then rst1.Close
If conn.State <> 0 Then conn.Close
Set rst1 = Nothing
Set conn = Nothing
Set ws = Nothing
Exit Sub
errHandle:
MsgBox Err.Number & ": " & Err.Description
GoTo Door
End Sub