Logicwurks Home Page

Links To Excel Code Examples

Tracing VBA Statements
Range/Wkb/Wks Variables
Add Grand Totals Using Ranges
Using Range Offset Property
Using Range Find Method
ConvertCellAddressToRange
Set Conditional Formatting
Union Of Ranges
Parse Range Strings
Delete Duplicate Rows
Delete Rows And Columns
Worksheet Variables
TypeName And TypeOf
Loop Through Worksheets
Loop Through Open Workbooks
Form Button Magic
Command Button Magic
Add Worksheets Dynamically
ImportExternalWorksheets
Find Last Row Or Column
Copy And Paste Special
Copy To Specific Cell Types
Range Copy With Filter
ExcelFileOpenSaveClose
ExcelFileOpenSaveCSV
Open An Excel File
Open An Excel File w/Params
Open An Excel File On Web
Save A Workbook
Save A Workbook Using mso
Clone A Workbook
Test If WEB URL Exists
Parse Using Split Command
Using Classes in Excel
TypeStatementStructures
Color Management
Convert Cell Color To RGB
Sort Methods 2003 - 2010
Sort Alpha/Numeric In ASCII
Search Using Match Function
Search Using Vlookup Function
Search Using Xlookup Function
Using Find Instead of Vlookup
Remove String Non-Printables
Auto_Open And Auto_Close
Initialize Form At Open
Edit Numerics In UserForm
Load Combo And List Boxes
Floating Sheet Combo Boxes
Advanced User Form Coding
Excel Events
Worksheet Change Events
Binary Search Of Array
Typecast Constants
Excel Error Handling
Handling Optional Parameters
Data Validation Drop Downs
Insert Data Validation Sub
Read A Text File w/Handle
Write A Text File w/Handle
Read a Binary File w/Handle
Update a Binary File w/Handle
Binary File Copy and Update
Read A Text Fiile w/Script
Text File Processing Examples
Test For Exists Or Open
Splash Screen
Dynamically Load Formulas
PaymentStreamsByDate
Date Examples
Date Find Same Days
Convert Month To Number
Initialize Arrays
Load Arrays Using Evaluate
ChartsAndGraphsVBA
Redim An Array
Reassign Button Action
Timer Functions
Legacy Calendar Control
Excel 2010 Date Picker
Date Picker Alternative
Generate Multiple Worksheets
Read Access Data Into Excel
Send Outlook Email w/Attach
Copy AutoFilters To Sheets
Export A Text File
Get Windows User Name
VBA Format Statement
Manipulate Files via VBA
Dynamically Load Images
Loop Through Worksheet Objects
Loop Through Form Objects
Loop Through Files with DIR
Active-X Checkboxes
Add Forms Checkboxes Dynam
Paste Pictures Into Excel
Copy Pictures Sheet To Sheet
Copy Pictures Sheet To Sheet
Create Forms Buttons With VBA
Extract Filename From Path
Convert R1C1 Format to A1
Special Cells Property
Insert Cell Comments

Links To Access Code Examples

DAO Versus ADODB
SearchVBACodeStrings
Interface Excel With Access
Create Form Manually
Create Recordset With AddNew
Multi-Select List Boxes
Update Field(s) In A Recordset
Update Excel Pivot From Access
Import A Tab Delimited File
Export Excel FileDialog
Create Excel Within Access
Open Excel Within Access
Open Excel OBJ From Access
Format Excel From Access
Control Excel via Access VBA
On Error Best Practices
Import Tab Delim w/WinAPI
Initialize Global Variables
Using TempVars For Globals
Access Error Handling
Loop Through Form Controls
Insert A Calendar Control
Create A Filtered Recordset
Populate Combo Boxes
Bookmarks And Forms
Combo Box Multiple Sources
Passing Form Objects
Create VBA SQL Statements
Create Dynamic Queries
Display File Images On A Form
Manipulate Files via VBA
Manipulate Files via Scripting
Number Subform Records
Reference Subform Objects
Parse Delimited Fields
Parameterized Queries (VBA)
Manipulating QueryDefs In VBA
FindFirst On Combined Keys
Dlookup Command
Dlookup In Form Datasheet
Execute SQL Delete Records
Commit Form To Table
Report With No Data
Reference Form Objects
DSNLess Connections To MySQL
Print Active Form Record
Count Records in Linked Tables
Delete Empty Tables
Open Linked SQL Tables

 

Manipulate QueryDefs From VBA

QueryDefs are stored queries that reside in Access. These QueryDefs can be opened and modified using VBA. Sometimes it is useful to modify an original stored QueryDef by adding additional filters or modifying the SQL String.

For a technical explanation of QueryDefs, See QueryDefs

The code below shows how to modify an original stored query by adding a dynamic WHERE clause, then execute the modified version to append records to a table.

Program Code

Private Sub cmdExportToExcel_Click()
' ****************************************************************
' Sample Of Using QueryDefs To Modify A Stored Query
' ****************************************************************
Dim cdlg As New CommonDialogAPI
Dim db As DAO.Database
' ****************************************************************
' Define Original Stored QueryDef Created With Query Builder
' ****************************************************************
Dim qd As DAO.QueryDef

' ****************************************************************
' Define New Temporary QueryDef Created By Adding a WHERE Clause
' ****************************************************************
Dim qdNew As DAO.QueryDef

' ****************************************************************
' Define Variables Used To Construct New Modified SQL Statement
' ****************************************************************
Dim strSQL As String
Dim intLenSQL As Integer

' ****************************************************************
' Delete The Contents of the Target Table For an Append Query
' ****************************************************************
DoCmd.SetWarnings False
DoCmd.OpenQuery "qryDeleteCombinedExplosionsReportFormatPic1", acViewNormal, acEdit
DoCmd.SetWarnings True

' ****************************************************************
' Bring In The Original QueryDef (Instantiate It)
' ****************************************************************
Set db = CurrentDb()
Set qd = db.QueryDefs("qryListInventoryAvailablePicsCreate")

' ****************************************************************
' Extract The SQL from the Original QueryDef
' ****************************************************************
strSQL = qd.SQL

' ****************************************************************
' Remove the Ending ";" and Space Characters from Original SQL
' ****************************************************************
intLenSQL = Len(strSQL) - 3
strSQL = Left(strSQL, intLenSQL)

' ****************************************************************
' Depending Upon The Type of SQL Modification Required Append
' a New WHERE Clause At The End Of The Original Query
' (1) Append WHERE BodyCode IN ("Value1", "Value2", "Value3);
' (2) Append WHERE BodyCode = "Value";
' ****************************************************************
If strSelectedBodyCode = "" Or IsNull(strSelectedBodyCode) _
    Or strSelectedBodyCode = "ALL" Then
    If strMultipleSelectFilter <> "" Then
        strSQL = strSQL & " WHERE tblCombinedExplosionsReportFormatPic.BodyCode " & _
        strMultipleSelectFilter & ";"
    End If
Else
    strSQL = strSQL & " WHERE tblCombinedExplosionsReportFormatPic.BodyCode = " & """" & strSelectedBodyCode & """" & ";"
End If

' ****************************************************************
' Close The Original Query without any Modifications
' ****************************************************************
qd.Close
Set qd = Nothing

' ****************************************************************
' Create A New Temporary QueryDef with the Modified SQL string
' The "" Creates a Temporary QueryDef That Is Not Saved
' ****************************************************************
Set qdNew = db.CreateQueryDef("", strSQL)

' ****************************************************************
' Execute the Modified QueryDef And Append Data To The Table
' ****************************************************************
qdNew.Execute dbFailOnError

' ****************************************************************
' Close The Temporary QueryDef Without Saving It
' ****************************************************************
qdNew.Close
Set qdNew = Nothing

End Sub

Program Code For a SELECT (Not Action) Query

Option Compare Database
Option Explicit

Public Sub FCSTTestSelectQuery()
' ********************************************************************************
' This Code Will Create a new SELECT Query or Update an Existing Select Query
' The db.Execute command can not be used on SELECT queries
' ********************************************************************************

Dim strLogicalCompareOperator As String
Dim strSQLForSelect As String
Dim db As DAO.Database
Dim qDef As DAO.QueryDef

Set db = CurrentDb()
strLogicalCompareOperator = "<=""B""))"

strSQLForSelect = "SELECT tblFCSTByStyleColorSizeDetail.SalesRep, tblFCSTByStyleColorSizeDetail.Account, tblFCSTByStyleColorSizeDetail.BodyCode, " & _
"tblFCSTByStyleColorSizeDetail.Style, tblFCSTByStyleColorSizeDetail.Color, tblFCSTByStyleColorSizeDetail.SizeDescription, " & _
"tblFCSTByStyleColorSizeDetail.ForecastYearMonth, Sum(tblFCSTByStyleColorSizeDetail.Quantity) AS ActualQty, " & _
"Sum(tblFCSTByStyleColorSizeDetail.Quantity) AS ForecastQty, First(tblFCSTByStyleColorSizeDetail.WholesalePrice) AS Wholesale, " & _
"Sum(tblFCSTByStyleColorSizeDetail.BookedUnits) AS BookedUnits, tblFCSTByStyleColorSizeDetail.ReportingYearMonth " & _
"FROM tblFCSTByStyleColorSizeDetail " & _
"GROUP BY tblFCSTByStyleColorSizeDetail.SalesRep, tblFCSTByStyleColorSizeDetail.Account, tblFCSTByStyleColorSizeDetail.BodyCode, " & _
"tblFCSTByStyleColorSizeDetail.Style, tblFCSTByStyleColorSizeDetail.Color, tblFCSTByStyleColorSizeDetail.SizeDescription, " & _
"tblFCSTByStyleColorSizeDetail.ForecastYearMonth, tblFCSTByStyleColorSizeDetail.ReportingYearMonth, " & _
"tblFCSTByStyleColorSizeDetail.SizeNumber, tblFCSTByStyleColorSizeDetail.ForecastYearMonth " & _
"HAVING (((tblFCSTByStyleColorSizeDetail.SalesRep)" & _
strLogicalCompareOperator & _
" ORDER BY tblFCSTByStyleColorSizeDetail.SalesRep, tblFCSTByStyleColorSizeDetail.Account, " & _
"tblFCSTByStyleColorSizeDetail.BodyCode, tblFCSTByStyleColorSizeDetail.Style, tblFCSTByStyleColorSizeDetail.Color, " & _
"tblFCSTByStyleColorSizeDetail.SizeNumber, tblFCSTByStyleColorSizeDetail.ForecastYearMonth;"

GoTo UpdateExistingQuery
' ********************************************************************************
' Create A New SELECT Query That Didn't Exist Before
' ********************************************************************************
Set qDef = db.CreateQueryDef("qryFCSTSelectiveExport", strSQLForSelect)
qDef.Close
Set qDef = Nothing
Set db = Nothing
DoCmd.OpenQuery "qryFCSTSelectiveExport", acViewNormal

' ********************************************************************************
' Update An Existing Query Already Viewable from the List of Access Objects
' ********************************************************************************
UpdateExistingQuery:
Set qDef = db.QueryDefs("qryFCSTSelectiveExport")
qDef.SQL = strSQLForSelect
qDef.Close
Set qDef = Nothing
Set db = Nothing
DoCmd.OpenQuery "qryFCSTSelectiveExport", acViewNormal

End Sub