param_substitution.ods (21.1 KB)
OK, this took some time. Please register my sample database
as “FilterData” and store the attached spreadsheet in a trusted directory where documents are allowed to run macros.
A macro refreshes the linked database ranges “Import2”,“Import3” and “Import4” on document open. These database ranges reside on Sheet2.
The first sheet contains a form and a 4 cells B2:B5 where you can enter optional filter criteria.
The 4 cells have some validation for the criteria input based on the linked datbase ranges.
The form is linked to the database’s parameter query “ParamFilter” which filters by a from-date, until-date, a category and a person. Each parameter is optional. Missing parameters are ignored.
SELECT * FROM "Data"
WHERE ( "PID" = :paramP OR :paramP IS NULL )
AND ( "CID" = :paramC OR :paramC IS NULL )
AND ( "D" >= :paramD1 OR :paramD1 IS NULL )
AND ( "D" <= :paramD2 OR :paramD2 IS NULL )
The form’s push button simply reloads the form.
The form has a hidden control named “ParamsRange” which contains the name of a range named “Parameters” (Sheet2.J2:M3).
The named range specified by the hidden control contains the 4 names of the query parameters in row #1 (paramD1, paramD2, paramP and paramC) and the corresponding criteria values from the first sheet in row #2. Any missing criterion is represented by error value #N/A.
Whenever the form is loaded or reloaded by any means, the form’s event “Fill Parameters” calls a macro.
The macro reads the named range specified by the hidden control “ParamsRange” and fills the query parameters with the values from row #2 according to the corresponding parameter names in row #1.
The hidden control makes it possible to use the same trick with different forms and different parameter ranges within the same document without writing a modified macro. Just add a hidden control “ParamsRange” where you specify the named cell range, filling up the parameters.