ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   SQL Query Function (https://www.excelbanter.com/excel-programming/379717-sql-query-function.html)

Stevek

SQL Query Function
 
Hello all,

I am trying to create a function that returns the result of an SQL query.
The best I've come up with is to use a Query Table. I pass the function two
parameters and the query returns a single value (a count of some records).
Is there maybe an easier way?? I have a lot of values to add and they need
to change based on the parameters passed.

Any Help Would Be appreciated..
TIA
Steve

Here's my code...
------------------------------------------------------------------------------------------------------
Function RunQuery(p1,p2)

Application.Volatile

Dim ConnString As String
Dim SQLString As String
ConnString = "ODBC;DSN=;UID;PWD=;Database;"

Select Case p1
Case 1
SQLString = "SELECT Count(*) AS nCount FROM table1 WHERE name =
" & p2
Case 2
SQLString = "SELECT Count(*) AS uCount FROM table2 WHERE user =
" & p2
Case 3
SQLString = "SELECT ......."
End Select

With ActiveSheet.QueryTables.Add(Connection:=ConnString ,
Destination:=ActiveCell, Sql:=SQLString)
.Name = rep & "_" & qs
.Set value
.......
.Set value
.Refresh
End With
RunQuery = ActiveSheet.QueryTables(p2 & "_" & p1)

End Function
------------------------------------------------------------------------------------------------------




All times are GMT +1. The time now is 10:23 PM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com