After much help from 2 Forum members I succeeded in running a query with parameters supplied by VBA.
The code I used is:-
Sub Comparisons()
Dim FROM1, FROM2, TO1, TO2 As Date
Dim strSQL As String
FROM1 = InputBox("Date from", "Input")
TO1 = InputBox("Date to", "Input")
FROM2 = DateAdd("yyyy", -1, FROM1)
TO2 = DateAdd("yyyy", -1, TO1)
FROM2 = DateValue(FROM2) ' needed to ensure variable is a date
TO2 = DateValue(TO2)
FROM1 = DateValue(FROM1)
TO1 = DateValue(TO1)
strSQL = "SELECT SalesComp.Expr4, SalesComp.WT_NOMCC, Sum(SalesComp.WT_NET_TOTAL) AS SumOfWT_NET_TOTAL INTO SumComp FROM SalesComp WHERE (((SalesComp.WM_INVOICE_DATE) > # " & FROM1 & " # AND(SalesComp.WM_INVOICE_DATE) < # " & TO1 & "#) OR (( SalesComp.WM_INVOICE_DATE) > #" & FROM2 & " # AND (SalesComp.WM_INVOICE_DATE) < # " & TO2 & " #)) GROUP BY SalesComp.Expr4, SalesComp.WT_NOMCC;"
CurrentDb.QueryDefs("SUMSalesComp").SQL = strSQL
DoCmd.OpenQuery "SUMSalesComp"
End Sub
This produced eg. this SQL string
SELECT SalesComp.Expr4, SalesComp.WT_NOMCC, Sum(SalesComp.WT_NET_TOTAL) AS SumOfWT_NET_TOTAL INTO SumComp
FROM SalesComp
WHERE (((SalesComp.WM_INVOICE_DATE) > # 01/09/2009 # AND(SalesComp.WM_INVOICE_DATE) < # 30/09/2009#) OR (( SalesComp.WM_INVOICE_DATE) > #01/09/2008 # AND (SalesComp.WM_INVOICE_DATE) < # 30/09/2008 #))
GROUP BY SalesComp.Expr4, SalesComp.WT_NOMCC;
I started to find anamalous results caused, I found, by the Query grid transposing some of the dates.
The SQL view was the same as the VBA SQL string but the grid transposed the day and month of the first and third date in the string to 09/01/2009 , and it was this version that produced the anomalous results.
How can I stop this from happening