Thread: Query Macro
View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
K Dales[_2_] K Dales[_2_] is offline
external usenet poster
 
Posts: 1,163
Default Query Macro

Tricky, but I like a challenge! MSQuery can take parameters, but not as
query or table names, just as selection criteria or for use in expressions.
The best thing I can think to do is to set up a basic querytable and then,
before refreshing, use VBA code to change the SQL query text
(querytable.commandtext) to customize it to your desires. You could do this
as part of the QueryTable.BeforeRefresh event procedure.

Using MSQuery, set up a simple query with any one of your Access queries -
just get a resulting querytable set up that matches one possible set of
parameters. Without knowing more about your database and spreadsheet I
can't develop this idea fully, but here is code that parses the SQL string
into its SELECT, FROM and WHERE components (assuming that is all we have!):

Public Sub ParseSQL()

Dim SELECTTxt As String, FROMTxt As String, WHERETxt As String
Dim TextPos As Integer

SQLTxt = Sheets("Sheet2").QueryTables(1).CommandText
TextPos = InStr(SQLTxt, vbCrLf & "FROM ")
SELECTTxt = Left(SQLTxt, TextPos - 1)
TextPos = InStrRev(SQLTxt, vbCrLf & "WHERE ")
WHERETxt = Right(SQLTxt, Len(SQLTxt) - TextPos + 1)
FROMTxt = Trim(Replace(SQLTxt, SELECTTxt, ""))
FROMTxt = Trim(Replace(FROMTxt, WHERETxt, ""))

MsgBox SELECTTxt
MsgBox FROMTxt
MsgBox WHERETxt

End Sub

Now (knowing the form of your query and the parameters you are getting from
your spreadsheet) you could use your VBA code to change these as necessary.
Substitute the Access query name in the FROMTxt with the cell value you want
to use to select the query. Substitute any other parameters in the WHERETxt
with your new parameters from the spreadsheet. Put this back together:

Sheets("Sheet2").QueryTables(1).CommandText = SELECTTxt & vbCrLF & FROMTxt &
vbCrLf & WHERETxt

Then refresh the query.

I have not had a chance to fully test this, but it seems to me it should
work. Hope I gave you at least an idea to work on.

"Steve" wrote:

Is there a way to create a macro that would look in a certain cell in a
worksheet to pick which query in Access to use? All queries in Access would
have the same layout. I also want to use parameters that are in certain cell
in the same worksheet.