To run SQL from within Excel where a sheet can act as a database / table, use the modified version of Mechanic's SQLJuicer
Code:Function SQLJuicer(strSQLString As String, strDataBaseAddress As String, Optional rngWhereToPasteRange As Range, Optional blnUsingAccessRDB As Boolean = True, Optional blnReturnListArrayInstead As Boolean = True) As Variant Dim adoConnection As Object 'New ADODB.Connection Dim adoRcdSource As Object 'New ADODB.Recordset Dim strDBPath As String Set adoConnection = CreateObject("ADODB.Connection") Set adoRcdSource = CreateObject("ADODB.Recordset") On Error GoTo Errs: strDBPath = strDataBaseAddress If blnUsingAccessRDB Then 'For Access DB adoConnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDBPath Else 'For Excel DB adoConnection.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strDBPath & "; Extended Properties=""Excel 12.0 Macro;HDR=YES"";" End If If UCase(Left(strSQLString, 6)) = "SELECT" Then adoRcdSource.Open strSQLString, adoConnection, 3 If rngWhereToPasteRange Is Nothing And blnReturnListArrayInstead = True Then If (adoRcdSource.BOF Or adoRcdSource.EOF) = False Then SQLJuicer = adoRcdSource.GetRows End If ElseIf Not rngWhereToPasteRange And blnReturnListArrayInstead = False Then With rngWhereToPasteRange .ClearContents .Cells(1).CopyFromRecordset adoRcdSource adoRcdSource.Close End With ElseIf Not rngWhereToPasteRange Is Nothing Then rngWhereToPasteRange.CopyFromRecordset adoRcdSource End If Else adoConnection.Execute strSQLString End If GoTo NormalExit Errs: MsgBox Err.Description, vbCritical, "Error!" Err.Clear: On Error GoTo 0: On Error GoTo -1 NormalExit: Set adoConnection = Nothing Set adoRcdSource = Nothing strDBPath = vbNullString End Function




Reply With Quote

Bookmarks