Anyway to Erase multiple forms, queries, etc in Access 2000? (In the designer that is).
This worked better for me. Trying to remove the elements in the loop itself kept having trouble. I just slapped the object names into an array, then deleted them afterward.
Public Sub DeleteAllFormsAndReports()
Dim accobj As AccessObject
Dim X As Integer
Dim iObjCount As Integer
Dim sObjectNames() As String
If MsgBox("Are you sure you want to delete all of the forms and reports?", vbCritical + vbYesNo) = vbYes Then
ReDim sObjectNames(0)
For Each accobj In CurrentProject.AllForms
ReDim Preserve sObjectNames(UBound(sObjectNames) + 1)
sObjectNames(UBound(sObjectNames)) = accobj.Name
Next accobj
For X = 1 To UBound(sObjectNames)
DoCmd.DeleteObject acForm, sObjectNames(X)
Next X
ReDim sObjectNames(0)
For Each accobj In CurrentProject.AllReports
ReDim Preserve sObjectNames(UBound(sObjectNames) + 1)
sObjectNames(UBound(sObjectNames)) = accobj.Name
Next accobj
For X = 1 To UBound(sObjectNames)
DoCmd.DeleteObject acReport, sObjectNames(X)
Next X
End If
End Sub
I create a lot of queries on the fly when a user performs certain actions. So, I'll create the query, then delete the query once they close the form. I do this under the On Close event. It runs regardless of whether the query was created or not. So, to prevent an error, I tell it to Resume Next.
Private Sub Form_Close()
On Error Resume Next
DoCmd.Close acReport, "EmployeeDetails"
DoCmd.DeleteObject acQuery, "MyEmployeeDetails"
End Sub
You can delete objects with VBA. Be sure to step backwards when deleting from a collection, for example, this code will delete quite a few objects:
Dim db As Database
Dim idx As Long
Dim strName As String
Set db = CurrentDb
''Forms
For idx = CurrentProject.AllForms.Count - 1 To 0 Step -1
strName = CurrentProject.AllForms(idx).Name
DoCmd.DeleteObject acForm, strName
Next idx
''Reports
For idx = CurrentProject.AllReports.Count - 1 To 0 Step -1
strName = CurrentProject.AllReports(idx).Name
DoCmd.DeleteObject acReport, strName
Next idx
''Modules
For idx = CurrentProject.AllModules.Count - 1 To 0 Step -1
strName = CurrentProject.AllModules(idx).Name
If strName <> "Module9" Then
DoCmd.DeleteObject acModule, strName
End If
Next idx
''Queries
For idx = db.QueryDefs.Count - 1 To 0 Step -1
strName = db.QueryDefs(idx).Name
If Left(strName, 4) <> "~sq_" Then
db.QueryDefs.Delete strName
Else
Debug.Print strName
End If
Next idx
''Relationships
For idx = db.Relations.Count - 1 To 0 Step -1
strName = db.Relations(idx).Name
If Left(strName, 4) <> "msys" Then
db.Relations.Delete strName
Else
Debug.Print strName
End If
Next idx
''Tables
For idx = db.TableDefs.Count - 1 To 0 Step -1
strName = db.TableDefs(idx).Name
If Left(strName, 4) <> "msys" Then
db.TableDefs.Delete strName
Else
Debug.Print strName
End If
Next idx
Related
i am trying to get the frequency of terms within a collection of variable length strings.The context is descriptions in an Access database. Would prefer to keep the solution in VBA. Delimiter is " " (space) character
Dim db As DAO.Database
Set db = CurrentDb()
Call wordfreq
End Sub
Function wordfreq()
Dim myCol As Collection
Dim myArray() As String
Dim strArray As Variant
Dim strDescr, strTerm, strMsg As String
Dim i, j As Integer
Set myCol = New Collection
strDescr = "here it should accept the table and display the result in seperate table"
' db.Execute "select columns from table"
myArray = Split(strDescr, " ")
For Each strArray In myArray
On Error Resume Next
myCol.Add strArray, CStr(strArray)
Next strArray
For i = 1 To myCol.Count
strTerm = myCol(i)
j = 0
For Each strArray In myArray
If strArray = strTerm Then j = j + 1
Next strArray
'placeholder
strMsg = strMsg & strTerm & " --->" & j & Chr(10) & Chr(13)
Next i
'placeholder
'save results into a table
MsgBox strMsg
End Function
See an example below using a Scripting.Dictionary object.
Function wordfreq()
Dim objDict As Object
Dim myArray() As String
Dim strInput As String
Dim idx As Long
Set objDict = CreateObject("Scripting.Dictionary")
strInput = "here it should accept the table and display the result in seperate table"
myArray = Split(strInput, " ")
For idx = LBound(myArray) To UBound(myArray)
If Not objDict.Exists(myArray(idx)) Then
'Add to dictionary with a count of 1
objDict(myArray(idx)) = 1
Else
'Increment counter
objDict(myArray(idx)) = objDict(myArray(idx)) + 1
End If
Next
'Test it
Dim n As Variant
For Each n In objDict.Keys
Debug.Print "Word: " & n, " Count: " & objDict(n)
Next
End Function
Output:
'Word: here Count: 1
'Word: it Count: 1
'Word: should Count: 1
'Word: accept Count: 1
'Word: the Count: 2
'Word: table Count: 2
'Word: and Count: 1
'Word: display Count: 1
'Word: result Count: 1
'Word: in Count: 1
'Word: seperate Count: 1
Edit
The process:
Loop through the Input recordset.
Split the Description into words.
Check if the word exist in Dictionary and add or
increment.
Add the Keys (words) and Values (count) of the aforementioned
Dictionary to the Output table.
To achieve this two helper functions have been set up:
One loops through the description recordset and returns a
Dictionary object filled with unique words as Keys and their
count as Values.
The other takes the above Dictionaryobject and adds it to the Output table.
You need to change [TABLE] to the name of your Input and Output tables.
Option Explicit
Sub WordsFrequency()
On Error GoTo ErrTrap
Dim rs As DAO.Recordset
Set rs = CurrentDb().OpenRecordset("SELECT Description FROM [TABLE] WHERE Description Is Not Null;", dbOpenSnapshot)
If rs.EOF Then GoTo Leave
With rs
.MoveLast
.MoveFirst
End With
If AddDictionaryToTable(ToDictionary(rs)) Then
MsgBox "Completed successfully.", vbInformation
End If
Leave:
If Not rs Is Nothing Then rs.Close
Set rs = Nothing
On Error GoTo 0
Exit Sub
ErrTrap:
MsgBox Err.Description, vbCritical
Resume Leave
End Sub
' Returns Scripting.Dictionary object
Private Function ToDictionary(rs As DAO.Recordset) As Object
Dim d As Object 'Dictionary
Dim v As Variant 'Words
Dim w As String 'Word
Dim i As Long, ii As Long 'Loops
Set d = CreateObject("Scripting.Dictionary")
For i = 1 To rs.RecordCount
v = Split(rs![Description], " ")
For ii = LBound(v) To UBound(v)
w = Trim(v(ii))
If Not d.Exists(w) Then d(w) = 1 Else d(w) = d(w) + 1
Next
rs.MoveNext
Next
Set ToDictionary = d
End Function
' Adds Dictionary object to table
Private Function AddDictionaryToTable(objDict As Object) As Boolean
On Error GoTo ErrTrap
Dim rs As DAO.Recordset
Dim n As Variant
Set rs = CurrentDb().OpenRecordset("[TABLE]")
With rs
For Each n In objDict.Keys
.AddNew
.Fields("Words").Value = n
.Fields("Counts").Value = objDict(n)
.Update
Next
End With
'all good
AddDictionaryToTable = True
Leave:
If Not rs Is Nothing Then rs.Close
Set rs = Nothing
On Error GoTo 0
Exit Function
ErrTrap:
MsgBox Err.Description, vbCritical
Resume Leave
End Function
The issue I am having is connect my Save_Record (suppose to save and push info) & btnExit (saves & exits) to push the information inputted on the form to be pushed out to the web database. The only way it will push the information is if I exit out, come back in and make a small change then it will push it out.
How can I achieve this without doing this?
Option Compare Database
Option Explicit
'-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**
Private Sub btnCancel_Click() '==**== undo changes
On Error Resume Next
RunCommand acCmdUndo
Err = 0
End Sub
'-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**
Private Sub btnExit_Click()
DoCmd.Close
End Sub
Private Sub cmdViewPDF_Click()
On Error GoTo Err_cmdViewPDF_Click
Dim stDocName As String
Dim stLinkCriteria As String
stDocName = "frm_Images"
DoCmd.OpenForm stDocName, , , stLinkCriteria
Exit_cmdViewPDF_Click:
Exit Sub
Err_cmdViewPDF_Click:
MsgBox Err.Description
Resume Exit_cmdViewPDF_Click
End Sub
'-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**
Private Sub Form_AfterUpdate()
'DoCmd.Save
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
[DT_MOD] = Now()
[MstrWinUser] = Forms!frFilter!txtWinUser
End Sub
'-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**
Private Sub MOREoperInfo_Click()
Dim DocName As String
Dim LinkCriteria As String
DoCmd.Save
DocName = "frmsearch"
DoCmd.OpenForm DocName, , , LinkCriteria
End Sub
'-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**-**
'Save record and close
Private Sub Save_Record_Click()
On Error GoTo Err_Save_Record_Click
[DT_MOD] = Now()
[MstrWinUser] = Forms!frmFilter!txtWinUser
'MsgBox "Saving frm_View"
'Save the record
'If there was a record already in txt box, we will assume it has been created in web
If Trim(txtEOCIncident.Value & vbNullString) = vbNullString Then
Me.txtEOCPushFlag = "0"
RunCommand acCmdSaveRecord
DoCmd.Save
Else
'SET EOC PUSH FLAG
Me.txtEOCPushFlag = "1"
RunCommand acCmdSaveRecord
DoCmd.Save
'TRY TO UPDATE WEB DATA
If (pushEOCData(Me.ID)) Then
'CLEAR PUSH FLAG AND SET PUSHDATE
Me.txtEOCPushFlag = "0"
Me.txtEOCPushDate = Now()
RunCommand acCmdSaveRecord
DoCmd.Save
End If
End If
Exit_Save_Record_Click:
Exit Sub
Err_Save_Record_Click:
MsgBox Error$
Resume Exit_Save_Record_Click
End Sub
'*** 08-20-13 New code. Creates PDF of the Report.
Private Sub btnSaveasPDF_Click()
On Error GoTo Err_btnSaveasPDF_Click
Dim db As Database, rs As Recordset
Dim vFN As String, vPATH As String, vFile As String
Dim blRet As Boolean
Dim stDocName As String
Dim strConstantName As String
stDocName = "rpt_Out"
'added 2014-09-02, MAB
strConstantName = "REPORT_FOLDER"
vPATH = Trim(DLookup("[ConstantValue]", "dbo_Constants", "[ConstantName] = '" & [strConstantName] & "'"))
If Forms!frm_View![DIST] = "1" Or Forms!frm_View![DIST] = "2" Or Forms!frm_View![DIST] = "3" Or Forms!frm_View![DIST] = "4" Then
vFN = Forms!frm_View![ID] & "_" & Forms!frm_View![Typeofreport] & "_" & Month(Now()) & "_" & Day(Now()) & "_" & Year(Now()) & "_" & Hour(Now()) & Minute(Now()) & ".pdf"
'vPATH = "\\...\...\Reports\"
vFile = vPATH & vFN
Else
MsgBox "Please enter your number." & vbCrLf & "It must be a single digit.", vbOKOnly Or vbInformation, "*****"
End If
'write to IMAGES
Set db = CurrentDb
Set rs = db.OpenRecordset("IMAGES")
rs.AddNew
rs!SPL_FILENAME = vFN
rs!SPL_ID = [Forms]![frm_View]![ID]
rs!SPL_MOD_DT = Format$(Now(), "mm/dd/yyyy")
rs!SPL_DOC_TYP = Forms!frm_View![DOC_TYP]
rs!SPL_FILELOC = vFile
rs!SPL_ACTIVE = "-1"
rs.Update
rs.Close
DoCmd.OpenReport "rpt_OUT", acViewPreview
DoCmd.OutputTo acReport, stDocName, acFormatPDF, vFile
MsgBox "An image of this report has been saved.", vbOKOnly Or vbInformation, "*****"
Exit_btnSaveasPDF_Click:
Exit Sub
Err_btnSaveasPDF_Click:
MsgBox Err.Description
Resume Exit_btnSaveasPDF_Click
End Sub
********************PUSHEOCDATA*******************************************
'* iSpillID is the value of SPILL_ID from Spills table for the
'* the record you want to update
'*
'*******************************************************************************
Public Function pushEOCData(iSpillID As Integer) As Boolean
Dim db As Database
Dim sSql As String
Dim strStoredProcSql As String
Dim qdef As DAO.QueryDef
Dim sEOCIncident As String
Dim rs As Recordset
Dim iEOCSpillID, iEOCMat1ID, iEOCMat2ID As Long
Dim iReturn As Integer
Dim dAmount1 As Double
Dim dAmount2 As Double
Dim sSpillResponse As String
Dim sMaterialResponse As String
Dim sEOCSpillID, sEOCMat1ID, sEOCMat2ID As String
Dim iFoundAt As Long
Dim iStart As Long
Dim sTemp As String
Dim bReturn As Boolean
Dim objSpillNode As IXMLDOMNode
Dim objMaterialsNodes As IXMLDOMNodeList
Dim objMaterialNode As IXMLDOMNode
pushEOCData = True
initWEBEoc
iEOCSpillID = -1
iEOCMat1ID = -1
iEOCMat2ID = -1
'RETRIEVE INCIDENT NUMBER FROM DATABASE and associated data
'from the database. Note: this is a stored procedure
Set db = CurrentDb
Set qdef = CurrentDb.CreateQueryDef("")
qdef.Connect = CurrentDb.TableDefs("usysWellHistory").Connect
qdef.ReturnsRecords = True
'
' This stored procedure is written to return a record set with
' fields named the same as in webeoc.
'
'strStoredProcSql = "EXEC RBDMS.SPILL_QUERY #N_SPILLID=" & iSpillID
strStoredProcSql = "{CALL RBDMS.SPILL_QUERY (" & iSpillID & ")}"
qdef.sql = strStoredProcSql
Set rs = qdef.OpenRecordset
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
sEOCIncident = rs!INCIDENTID_NUMBER
If Len(sEOCIncident) < 1 Then
pushEOCData = False
Exit Function
End If
'Get the data from webeoc.
'business rules say that we have to have data
'in webeoc to continue
iReturn = getSpillNode(sEOCIncident, objSpillNode)
If iReturn < 1 Then
'MsgBox "No WEBEoc data exists for EOC Incident: " & sEOCIncident
pushEOCData = False
Exit Function
End If
'grab the data id from the spill data, we will need this later to
'update the materials
sEOCSpillID = objSpillNode.Attributes.getNamedItem("dataid").Text
iEOCSpillID = CLng(sEOCSpillID)
If iEOCSpillID < 1 Then
pushEOCData = False
Exit Function
End If
bReturn = updateEOCSpillData(rs, objSpillNode)
If bReturn = False Then
pushEOCData = False
Exit Function
End If
dAmount1 = rs!AMOUNT1
dAmount2 = rs!AMOUNT2
'Get the materials records from webeoc for this incident number.
iResult = getMaterialNodes(sEOCSpillID, objMaterialsNodes)
If dAmount1 > 0 Then
'If webeoc has one or more materials records for the incident,
'grab the first record and update it with dbase values
If objMaterialsNodes.LENGTH > 0 Then
Set objSpillNode = objMaterialsNodes.Item(0)
'update materials
updateEOCMaterialData rs, objSpillNode, 1
Else
'insert materials
insertEOCMaterialData rs, 1, sEOCSpillID
End If
End If
If dAmount2 > 0 Then
'if webeoc has more than one materials record for the incident,
'grab the second record and update it.
If objMaterialsNodes.LENGTH > 1 Then
Set objSpillNode = objMaterialsNodes.Item(1)
'update materials
updateEOCMaterialData rs, objSpillNode, 2
Else
'insert materials
insertEOCMaterialData rs, 2, sEOCSpillID
End If
End If
Else
'MsgBox "No data needs to be pushed to webeoc for this spill."
pushEOCData = True
Exit Function
End If
rs.Close
End Function
Sincerely in the dark. My Code:
Public Property Get rowCount() As Integer
rowCount = Counter
End Property
Public Property Let rowCount(ByRef inte As Integer)
Counter = inte
End Property
Private Sub Form_Timer() 'Timer
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim Caption As Field, Form As Field, Count As Integer, holder As Integer, item As String
Dim strForms() As String
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset("MainMenu", dbOpenDynaset)
ReDim strForms(1 To rs.RecordCount())
If rs.RecordCount <> 0 Then
For c = 1 To rs.RecordCount() Step 1 '!!!THIS IS THE PROBLEM!!!
MsgBox CStr(c)
MsgBox rs("Caption")
strForms(c) = rs("Caption")
rs.MoveNext
MsgBox rs("Caption")
Next c
End If
rowCount = 1
holder = rowCount()
If holder <= rs.RecordCount() Then
Me.Command10.Caption = strForms(holder)
rowCount = holder + 1
Else
rowCount = 1
Me.Command10.Caption = strForms(holder)
End If
End Sub
I added all those message boxes in my effort to debug. All I need is that counter to go up. No idea why it is not. Why will this thing not increment?!
The best way is to use rs.MoveFirst, rs.MoveNext and rs.EOF to check for end of records. The following VBA will do what you want.
'Open up a recordset on our table
Set dbs = CurrentDb
Set rs = dbs.OpenRecordset("MyTable", dbOpenDynaset)
'Did we find any records?
If rs.RecordCount > 0 Then
'Move to first record
rs.MoveFirst
'Iterate through each record
Do
'Do stuff with the currentrecord
MsgBox ("Next record ID is: " + CStr(rs("ID")))
'Move to next record
rs.MoveNext
'Exit when we hit the end of the recordset
Loop While rs.EOF <> True
End If
'Close the recordset
rs.Close
Using the RecordCount property might be the problem.
It essesntially just counts the number of times rs.MoveNext had been called.
Try switching the code to a loop like this:
Dim L As Long
Do Until rs.EOF
L = L + 1
MsgBox rs.RecordCount
MsgBox L
rs.MoveNext
Loop
Access Recordsets aren't as easy as .NET DataTables but they've been around a lot longer.
http://msdn.microsoft.com/en-us/library/office/bb208624(v=office.12).aspx
Basically I want to flip the line number values in the two records when someone changes them in the subform
so if i have line:
12345 and I rename 5 to 3 I want 5 renumbered to 3 and 3 renumbered to 5 so I would have 12543 but they reshuffle to 12345 but the records switch places correctly
However I get an error (see below) and if I change record 1 it can't find any records
the code I have so far is:
Private Sub OrderLineNumber_AfterUpdate()
Dim rst As DAO.Recordset
Set rst = Me.Recordset
Dim recNum As Integer
Dim recVal As Double
Dim move As Integer
Dim i As Integer
recNum = Me.CurrentRecord
Me.Requery
DoCmd.GoToRecord , , acGoTo, recNum
recVal = rst!OrderLineNumber.Value
rst.MoveFirst
Do Until rst.EOF
i = rst!OrderLineNumber.Value
If i = recVal Then
move = Me.CurrentRecord
End If
rst!OrderLineNumber.Value = recVal #Here
DoCmd.GoToRecord , , acGoTo, recNum
rst!OrderLineNumber.Value = i
rst.MoveNext
Loop
End Sub
and is failing at #Here with error update or cancelupdate without add new or edit
Before changing a value on a DAO record you need to run the Edit method. And then you need to run the Update method after changing it.
Private Sub OrderLineNumber_AfterUpdate()
Dim rst As DAO.Recordset
Set rst = Me.Recordset
Dim recNum As Integer
Dim recVal As Double
Dim move As Integer
Dim i As Integer
recNum = Me.CurrentRecord
Me.Requery
DoCmd.GoToRecord , , acGoTo, recNum
recVal = rst!OrderLineNumber.Value
rst.MoveFirst
Do Until rst.EOF
i = rst!OrderLineNumber.Value
If i = recVal Then
move = Me.CurrentRecord
End If
rst.Edit
rst!OrderLineNumber.Value = recVal #Here
rst.Update
DoCmd.GoToRecord , , acGoTo, recNum
rst.Edit
rst!OrderLineNumber.Value = i
rst.Update
rst.MoveNext
Loop
End Sub
Here's a function I use that does something quite similar. I have a main form with buttons with up and down arrows on them, and a datasheet subform (continuous form would work too). Every row in the subform has a RowOrder field with a value in it starting from 1. These values get assigned as the user adds new records.
When the user wants to change the order of the records in the subform they just use the arrow buttons located on the main form. One thing not in my code here is checks for new record, or checks to see if they have no records entered. Another thing my function does not do is reorder or fix all the rows. It only affects the row in focus and the one above or below it. Here's the code:
Private Sub cmdUp_Click()
'Put an "Up" button on one of your forms and pass the function a correct form object
Call MoveCurrentRecordUpOrDown("Up", Me.subform1.Form)
End Sub
Private Sub cmdDown_Click()
'Put a "Down" button on one of your forms and pass the function a correct form object
Call MoveCurrentRecordUpOrDown("Down", Me.subform1.Form)
End Sub
Public Function MoveCurrentRecordUpOrDown(sDirection As String, frm As Form)
Dim lPos As Integer
Dim iCurRowOrder As Integer
iCurRowOrder = Nz(frm!RowOrder, 0)
'Check to see if the record is already up against one of the ends
Dim iChange As Integer
Select Case sDirection
Case "Up"
If iCurRowOrder = 1 Then Exit Function 'Cannot move record up
iChange = -1
Case "Down"
If iCurRowOrder = frm.Recordset.RecordCount Then Exit Function 'Cannot move record down
iChange = 1
End Select
lPos = frm.Recordset.AbsolutePosition + iChange
Dim rs As DAO.Recordset
Set rs = frm.RecordsetClone
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
Do Until rs.EOF = True
If rs!RowOrder = iCurRowOrder Then
rs.Edit
rs!RowOrder = iCurRowOrder + iChange
rs.Update
ElseIf rs!RowOrder = (iCurRowOrder + iChange) Then
rs.Edit
rs!RowOrder = iCurRowOrder
rs.Update
End If
rs.MoveNext
Loop
frm.Requery
If lPos > (frm.Recordset.RecordCount - 1) Then
lPos = (frm.Recordset.RecordCount - 1)
End If
frm.Recordset.AbsolutePosition = lPos
End If
rs.Close
Set rs = Nothing
End Function
I have a recordset that I want to export into Excel 2000 format (acSpreadsheetTypeExcel9). I believe I need to drop it into a table first then execute a DoCmd.TransferSpreadsheet (keeps it easy and it works). The user sets just a few parameters in the form, thus the Me. syntax you will see.
Here's the working code so far:
Select Case Me.Controls("frame_ChooseReport").Value
Case 1
sExecuteQuery = "qry_PDSR w/ Destruct Dates"
bHasProgramCode = True
sFileName = "Project_Doc_Submittal_Request_better"
Case 2
sExecuteQuery = "qry_PDSR w/Destruct Dates BE"
bHasProgramCode = False 'This is the only query here that doesn't have a Program Code parameter
sFileName = "Project_Doc_Submittal_Request_better_BE"
Case 3
sExecuteQuery = "qry_Project Documentation Submittal Request w/ Destruct Dates"
bHasProgramCode = True
sFileName = "Project_Doc_Submittal_Request_ENH"
Case 4
sExecuteQuery = "qry_Project_Doc_Submittal_Request_w_Destruct_Dates_HES_Installer"
bHasProgramCode = True
sFileName = "Project_Doc_Submittal_Request_Installer"
Case Else
Stop 'Error! This should never be reached!
End Select
'Execute query & save output to Excel
Set qdf = CurrentDb.QueryDefs(sExecuteQuery) 'Open the query
'Assign values to the query using the parameters option
If bHasProgramCode = True Then
qdf.Parameters(0) = Me.lbl_ProgramCodes.Section
qdf.Parameters(1) = Me.txt_StartDate
qdf.Parameters(2) = Me.txt_EndDate
Else
qdf.Parameters(0) = Me.txt_StartDate
qdf.Parameters(1) = Me.txt_EndDate
End If
sFullPath = Me.lbl_SaveTo.Caption & "\" & sFileName
Set rst = qdf.OpenRecordset 'Convert the querydef to a recordset and run it
If rst.BOF = True And rst.EOF = True Then
MsgBox "No records were found.", vbExclamation, "Empty recordset"
Exit Sub
End If
'Dump recordset into a table, export it to Excel, then delete it.
'Here is where the recordset needs to become a table.
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "qry_PDSR w/ Destruct Dates", sFullPath, True 'Export table to an Excel format
'Clean up!
DoCmd.DeleteObject acTable, gTEMP_TBL 'Done with the temporary table so delete it
rst.Close
qdf.Close
Set rst = Nothing
Set qdf = Nothing
Help/suggestions? Thank you.
Access 2010 in Windows 7
---------- FOLLOW UP ----------
Here's the query I added that will use the references of the opened form per Remou's suggestion:
SELECT dbo_PROJECT.PROJECTID, dbo_PROJECT.TITLE, dbo_PROJECT.PROGRAMCODE, dbo_PROJECT.PROJECTTYPE, dbo_PROJECT.REFERENCE, dbo_PROJECT.STATUS, dbo_PROJECT.PMC, dbo_TRANSACTION_SUM.STATUS, dbo_TRANSACTION_SUM.IMPORTEDDT, dbo_TRANSACTION_SUM.CHECKDT, dbo_PROJECT.NOTES, dbo_TRANSACTION_SUM.TRANSACTIONID, dbo_TRANSACTION_SUM.GL_ACCT, dbo_PROJECT_SUM.PAID_INCENT_TOTAL, dbo_TRANSACTION_SUM.AMOUNT
FROM ((dbo_INCENTIVE RIGHT JOIN dbo_PROJECT ON dbo_INCENTIVE.PROJECTID = dbo_PROJECT.PROJECTID) LEFT JOIN dbo_TRANSACTION_SUM ON dbo_INCENTIVE.INCENTIVEID = dbo_TRANSACTION_SUM.INCENTIVEID) LEFT JOIN dbo_PROJECT_SUM ON dbo_PROJECT.PROJECTID = dbo_PROJECT_SUM.PROJECTID
WHERE (((dbo_PROJECT.PROGRAMCODE) In ([Forms]![Submittal_Request_Report]![txt_ListProgramCodeSelections])) AND ((dbo_TRANSACTION_SUM.CHECKDT) Between [Forms]![Submittal_Request_Report]![txt_StartDate] And [Forms]![Submittal_Request_Report]![txt_EndDate]));
Here's the routine that is in the On_Exit event of the listbox:
Private Sub list_ProgramCodes_Exit(Cancel As Integer)
'Get selection from Program Code listbox and store it in a hidden textbox for the query.
Dim x As Long, sValue As String, ctlSource As Control
sValue = ""
Set ctlSource = Me!list_ProgramCodes
For x = 0 To ctlSource.ListCount - 1
If ctlSource.Selected(x) Then
sValue = sValue & ctlSource.Column(0, x) & ","
End If
Next
Me.txt_ListProgramCodeSelections.Value = Left(sValue, Len(sValue) - 1) 'Drop the last comma
Set ctlSource = Nothing
End Sub
Works great! The SQL line In ([Forms]![Submittal_Request_Report]![txt_ListProgramCodeSelections]) pulls the list of items in the hidden textbox (using a label didn't work) that was populated with the selection from the listbox on the form.
This is now the code for exporting the query:
Private Sub btn_RunReport_Click()
Dim sExecuteQuery As String, sFullPath As String, sFileName As String
On Error GoTo Err_btn_RunReport_Click
If Left(Me.lbl_SaveTo.Caption, 4) = "save" Then
MsgBox "Please select a folder to save the results to.", vbInformation, "No folder selected"
Exit Sub
End If
Select Case Me.Controls("frame_ChooseReport").Value
Case 1
sExecuteQuery = "qry_PDSR_Destruct_Dates_form"
sFileName = "Project_Doc_Submittal_Request.xls"
Case 2
sExecuteQuery = "qry_Project_Doc_Submittal Request w/ Destruct Dates_form"
sFileName = "Project_Doc_Submittal_Request_ENH.xls"
Case 3
sExecuteQuery = "qry_PDSR_w_Destruct_Dates_HES_Installer_form"
sFileName = "Project_Doc_Submittal_Request_Installer.xls"
Case Else
Stop 'Error! This should never be reached!
End Select
sFullPath = Me.lbl_SaveTo.Caption & "\" & sFileName
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, sExecuteQuery, sFullPath, True 'Export table to an Excel format
Exit_btn_RunReport_Click:
Exit Sub
Err_btn_RunReport_Click:
MsgBox Err.Description
Resume Exit_btn_RunReport_Click
End Sub
Thanks Remou!
I suggest you just set the sql of a query to a suitable string and then export the query:
sSQL="SELECT * FROM Table WHERE Field=" & me.MyText
If IsNull(DLookup("name", "msysobjects", "name='query1'")) Then
CurrentDb.CreateQueryDef "Query1", sSQL
Else
CurrentDB.QueryDefs("Query1").SQL = sSQL
End If
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Query1", sFullPath
You can create a query that references an open form:
SELECT Test.ID, Test.Data
FROM Test
WHERE Test.AField=[forms]![test]![pickone]