Also, I wanted to recommend a few minor changes as good practices:
- Option Compare Database
-
Option Explicit
-
-
Private Function ExportRpt()
-
On Error GoTo EH
-
Dim RS As Recordset
-
Dim qDf As QueryDef
-
Dim strSQL As String
-
Dim myLocation As String
-
Dim myFile As Long
-
-
strSQL = "SELECT ClientNumber FROM tblFileNames;"
-
Set RS = CurrentDb.OpenRecordset(strSQL)
-
With RS
-
If Not .RecordCount = 0 Then
-
.MoveFirst
-
Do While Not .EOF
-
DoCmd.DeleteObject acQuery, "MyQuery"
-
myLocation = !Ballot_Style
-
myFile = "P:\LPSOutputs\FinishedReports\test.xlsx"
-
strSQL = "SELECT * FROM QryData " & _
-
"WHERE ClientNumber='" & myMyLocation & "';"
-
Set qDf = CurrentDb.CreateQueryDef("MyQuery", strSQL)
-
DoCmd.TransferSpreadsheet acExport, , _
-
"MyQuery", myFile, False
-
.MoveNext
-
Loop
-
End If
-
.Close
-
End With
-
Set RS = Nothing
-
-
Exit Function
-
EH:
-
MsgBox "There was an error exporting the client data!" & vbCrLf & vbCrLf & _
-
"Error: " & Err.Number & vbCrLf & _
-
"Description: " & Err.Description & vbCrLf & vbCrLf & _
-
"Please contact your Database Administrator.", vbCritical, "WARNING!"
-
Exit Function
-
End Function
I included the
Option Compare
and
Option Explicit
statements (You may already have these in the module, but it is good to be sure that you always use them.
I've also listed this function as
Private
, which simply mean that it can only be used on the particular Form in which it is found. This can be set to
Public
, if you want to use it throughout your project.
Notice how each set of nested statements is indented accordingly. This helps you in the future when you have to troubleshoot (and helps others, too). You may have found the missing
Do While
had you done so.
I've included a more robust Error handling procedure--which is recommended for all procedures.
In lines 12-13, I've assigned the SQL string to the variable and then set the recordset using the variable. This is not required, but as your SQL strings become more complex, it allows you to trouble shoot the value of the variable if the recordset does not execute properly.
Also, notice lines 15 and 17.
.RecordCount
and
.EOF
are not quite the same thing. Whenever checking to see if there are any contents in a Recordset, I always recommend using
.RecordCount
, as sometimes (
very rarely)
.EOF
can give a false negative if there is only one record.
Hope this hepps!