473,386 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Code found not sure how to use it exactly

I found a post with some code I thought would work for my needs but I don't know how to use it exactly.

The post (with the code) can be seen here:
Best way to prompt for report parameters in microsoft access

I have the form for the date inputs set up, I have the reports OnOpen using [Event Procedure] and the code pasted in there. When I generate the report, the pop up form is triggered but once I enter the dates it doesn't do anything. The original post doesn't go into details about the use of the code so I thought I'd ask here.

Here are the two code snippets:
Expand|Select|Wrap|Line Numbers
  1. Private Sub Report_Open(Cancel As Integer)
  2.   Dim dteStart as Date
  3.   Dim dteEnd As Date
  4.  
  5.   DoCmd.OpenForm "dlgGetDates", , , , , acDialog 
  6.   If IsLoaded("dlgGetDates") Then
  7.      With Forms!dlgGetDates
  8.        dteStart = !StartDate
  9.        dteEnd = !EndDate
  10.      End With
  11.      Me.Recordsource = "SELECT * FROM MyTable WHERE DateField Between #" _
  12.         & dteStart & "# AND #" & dteEnd & "#;" 
  13.      DoCmd.Close acForm, "dlgGetDates"
  14.   End If
  15. End Sub
AND:
Expand|Select|Wrap|Line Numbers
  1. Function IsLoaded(ByVal strFormName As String) As Boolean
  2.  ' Returns True if the specified form is open in Form view or Datasheet view.
  3.   Const conObjStateClosed = 0
  4.   Const conDesignView = 0
  5.  
  6.   If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
  7.      If Forms(strFormName).CurrentView <> conDesignView Then
  8.         IsLoaded = True
  9.      End If
  10.   End If
  11. End Function
I'm sure I have to change MyTable to my actual table [Calls] and DateField to my field name [Resolved Date] but then what?

Thanks,
Terry
Aug 11 '16 #1
5 1098
nico5038
3,080 Expert 2GB
I usually try to prevent prompting for report parameters, as people use to make typo's, causing an eroneous report or an empty report.
My approach is to have the parameters on the form and test in my form code or it's resulting in a filled report. When that's the case I activate the [Print] button and show the report in preview mode, still allowing the user to cancel the printing when (s)he has second toughts about the selection.

Idea ?

Nic;o)
Aug 11 '16 #2
Cbold
6
Not sure about the code, here is what I do for date ranges
On the form you created, name one field begindate and the other enddate.
The user will enter the dates on this form. This form could also have a list box with your reports, or command buttons for the report...I always call this form F_SW.

In your query, set the criteria of the date field as
BETWEEN [FORMS].[nameofform].[begindate] AND [FORMS].[nameofform].[enddate]

Now when the report is select it will query for the date range. Hope this helps. If I'm not on the right track, please post.


I use this in all my report queries.
Aug 17 '16 #3
PhilOfWalton
1,430 Expert 1GB
Have a look at my article https://bytes.com/topic/access/answe...filter-reports

Phil
Aug 17 '16 #4
Good morning all.

I have this working, somewhat, but not as I'd like nor as, I think, it was intended to work.

Here is what I'd like to accomplish.

The way I read the code is that when the report is opened/selected (in the reports drop-down list) the parameters pop-up form is supposed to load then put in the dates - and here is where a bit of code is throwing me - once the dates are added then what? There is no code for an "OK" button or a "Run Query" button so how does one tell the pop-up form to run the code behind the form?

From my understanding this bit of code goes on the reports "On Load" event which pops up the date form.
Expand|Select|Wrap|Line Numbers
  1. Private Sub Report_Open(Cancel As Integer)
  2. Dim dateStart As Date
  3. Dim dateEnd As Date
  4.  
  5.     DoCmd.OpenForm "dlgParameters", , , , , acDialog
  6.         If IsLoaded("dlgParameters") Then
  7.             With Forms!dlgParameters
  8.             dateStart = !txtStartDate
  9.             dateEnd = !txtEndDate
  10.         End With
  11.     Me.RecordSource = "SELECT * FROM [Calls] WHERE [Resolved Date] Between #" & dateStart & "# AND #" & dateEnd & "#;"
  12.     'DoCmd.Close acForm, "dlgParameters"
  13.         End If
  14. End Sub
  15.  
And the IsLoaded function as well:
Expand|Select|Wrap|Line Numbers
  1. Function IsLoaded(ByVal strFormName As String) As Boolean
  2.  ' Returns True if the specified form is open in Form view or Datasheet view.
  3.   Const conObjStateClosed = 0
  4.   Const conDesignView = 0
  5.  
  6.   If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
  7.      If Forms(strFormName).CurrentView <> conDesignView Then
  8.         IsLoaded = True
  9.      End If
  10.   End If
  11. End Function
  12.  
This bit of code:
Expand|Select|Wrap|Line Numbers
  1. DoCmd.Close acForm, "dlgParameters"
I commented out as it was throwing errors. I put the close code on an "OK" button on the date form:
Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdOK_Click()
  2.     DoCmd.OpenReport "rptCalls - Resolved", acViewPreview
  3.     DoCmd.Close acForm, "dlgParameters"
  4. End Sub
Here is where the code starts to break, at least in the way I want it to work.

Everything I have setup now works BUT the report has to be opened in the background before opening the date form for the code to work and run.

The way I thought this would work is when the report is selected the date form would pop up (which it does - more below) the dates would be entered (missing run code here for the original code) then the report would be generated.

The way I would like this to work is the way I thought it would work when I found the code. Select report, date form opens, enter dates, --- run code and generate the report.

I have tried everything I can think of but I keep running into errors. I've tried with using a query but get errors then too.

The way it is now I get error "94" Invalid use of Null if I try to load the report first. The line highlighted is
Expand|Select|Wrap|Line Numbers
  1. dateStart = !txtStartDate
so it's looking for form data before I get to enter the dates.

So how can I get this to work as intended? Select report, dlgParameters pops up (and does not error), I enter the dates for the report click the "OK" button and the report generates and the pop up form closes?

The only code for the report is the IsLoaded function and the "On Open" event to pop up the form "dlgParameters". Also, as I have it now there is not record source or control source for the report.

The form "dlgParameters" is unbound, no record or control source, has two text boxes for txtStartDate and txtEndDate and an "OK" and "Cancel" buttons with the following code for the buttons:
Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdCancel_Click()
  2.     DoCmd.Close
  3. End Sub
  4.  
  5. Private Sub cmdOK_Click()
  6.     DoCmd.OpenReport "rptCalls - Resolved", acViewPreview
  7.     DoCmd.Close acForm, "dlgParameters"
  8. End Sub
  9.  
I'm not sure what I've done right or wrong here and would love some help/guidance.

Terry
Aug 24 '16 #5
jforbes
1,107 Expert 1GB
There are a lot of different ways you can fire off a Report:
  • You can have the Parameters in the Query that the report is based on. These can point to a Form or Variables.
  • Display a parameters dialog box in the Form's on open event to change the Filter or Recordsource.
  • Open the Form with a Filter.
  • Set some TempVars or OpenArgs when opeing the Report and then having the Report decipher the values on open.

I'm sure there is more, but in my experience, nearly all of these different ways of opening an Report are a mistake and error prone except for opening a report with a Filter. Why? It mostly has to do with the flow of the code. It's best to write code that funnels your user down a chute or slide to the bottom of the cliff instead of throwing them off a ledge. By putting a parameter in the Report's Query or writing code in Report Open Event, your just throwing the code execution at the Report and expecting it to handle things from there. So the report is responsible for gathering and validating the parameters and handling error when these parameters are wrong.

I think Both Nico and Phil have tried to guide you towards a more controlled approach by gathering and validating the users parameters before opening the Report. I haven't looked at Phil's approach, but I would recommend giving it a shot.

What I typically do is write the Report with as little code as possible and write it in a way that it runs wide open and returns all the results. In practice, you wouldn't want to run the Report like this, so then I often write a wrapper routine (or a launcher) that calls the Report. This is where the validation is accomplished on the parameters and only if the validation is passed is the Report executed. Sometimes the wrapper/launcher will prompt for information if the workflow calls for it, otherwise it can kick out an error. Here is simple example of a wrapper:
Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdNewBlankQuote_Click()
  2.     gNewQuoteNumber = ""
  3.     DoCmd.OpenForm "QuoteNew", acNormal, , , acFormAdd, acDialog    
  4.     If Len(gNewQuoteNumber) > 0 Then
  5.         DoCmd.OpenReport "Quotes", , , "QuoteNumber='" & gNewQuoteNumber & "'"
  6.     End If    
  7. End Sub
When the button is clicked a global variable is reset to a blank value, then a Dialog box is displayed to get the information needed from the User. After the Dialog box is closed, the global variable is checked to make sure it has a value, and if it does the Report is run with a filter applied to show only the information needed.

Here is a variation on the above theme:
Expand|Select|Wrap|Line Numbers
  1. Public Sub printQuote(Byref sQuoteNumber As String)
  2.     If Len(sQuoteNumber) = 0 Then
  3.         gNewQuoteNumber = ""
  4.         DoCmd.OpenForm "QuotePrompt", acNormal, , , , acDialog
  5.         sQuoteNumber = gNewQuoteNumber 
  6.     End If
  7.     If Len(sQuoteNumber) > 0 Then
  8.         DoCmd.OpenReport "Quotes", , , "QuoteNumber='" & sNewQuoteNumber & "'"
  9.     End If    
  10. End Sub
In this variation, if the QuoteNumber is supplied, the Report is printed, otherwise the QuoteNumber is prompted for by the Dialog box and the Report is only printed if the value is supplied.

Lastly, to hammer the point home, here is an example of more complex wrapper/launcher (I've cleaned it up and hidden some stuff to attempt to make it read easier):
Expand|Select|Wrap|Line Numbers
  1. Public Function genBOMPDF(ByRef sQuoteNumber As String) As String
  2. On Error GoTo ErrorOut
  3.  
  4.     Dim sFileName As String
  5.     Dim sWildCardFileName As String
  6.     Dim iErrorLevel As Integer
  7.     Dim sReportName As String
  8.     Dim sError As String
  9.     Dim sSQL As String
  10.     Dim sDestination As String
  11.     Dim sTempDirectory As String
  12.  
  13.     ' Validate and Variables
  14.     genBOMPDF = ""
  15.     iErrorLevel = 1
  16.     If Len(sQuoteNumber) = 0 Then
  17.         Call msgBoxError("A Quote Number is Required to generate a BOM PDF.")
  18.         GoTo ExitOut
  19.     End If
  20.     setStatus ("Creating Preview...")
  21.     sFileName = sQuoteNumber & "_BOM_" & getStringDateTime & ".PDF"
  22.     sWildCardFileName = sQuoteNumber & "_BOM_?????????????.PDF"
  23.     sReportName = "BOM"
  24.     sTempDirectory = getApplicationDirectory & "\Temp\"
  25.     Call establishFolder(sTempDirectory)
  26.  
  27.     ' Create Quote
  28.     DoCmd.OpenReport sReportName, acViewPreview, , "QuoteNumber='" & sQuoteNumber & "'"
  29.     setStatus ("Creating PDF...")
  30.     iErrorLevel = 2
  31.     DoCmd.OutputTo acOutputReport, sReportName, acFormatPDF, sTempDirectory & sFileName, True
  32.     iErrorLevel = 3
  33.     DoCmd.Close acReport, sReportName
  34.  
  35.     iErrorLevel = 4
  36.     setStatus ("Adding Attachment")
  37.     If createAttachment(sTempDirectory & sFileName, sDestination, 3, sQuoteNumber, sFileName, "Quote BOM") = 0 Then
  38.         GoTo ExitOut
  39.     End If
  40.  
  41.     iErrorLevel = 5
  42.     setStatus ("Archiving Previous BOMs")
  43.  
  44.     sSQL = "UPDATE Attachment SET Deleted=-1 WHERE Attachment LIKE '" & Replace(sDestination, sFileName, sWildCardFileName) & "' AND Attachment <> '" & sDestination & " '"
  45.     Call executeSQL(sSQL)
  46.  
  47.     genBOMPDF = sFileName
  48.  
  49. ExitOut:
  50.     setStatus ("")
  51.     Exit Function
  52. ErrorOut:
  53.     Select Case iErrorLevel
  54.         Case 2
  55.             gErrorMessage = "Could not create the Report, please make sure the file '" & gQuoteDirectory & sFileName & "' is not open by Acrobat or another program." & vbCrLf & vbCrLf & "The actual error message is:  " & Err.Description
  56.         Case Else
  57.     End Select
  58.     Call customErrorHandler(mProcedureName, True, Err, Erl, gErrorMessage)
  59.     Resume ExitOut
  60. End Function
Aug 24 '16 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Steve | last post by:
I will be starting to work on an e-commerce web site pretty soon, and one thing the user would like to do is to have a part of the site that he could use in the store for recording the transaction....
4
by: DS | last post by:
Hi, I wrote this code, It works except I need to reference a Table called Employees, How is this done? If Display = EmployeeID Then DoCmd.RunMacro "Log On" Else DoCmd.OpenForm "StartUp" End...
3
by: Simon2005 | last post by:
Hi, This is a segement of code taken from Warren Young's FAQ on Winsock @ http://tangentsoft.net/wskfaq/ struct Connection { SOCKET sd; char acBuffer; int nCharsInBuffer; Connection(SOCKET...
17
by: warlord | last post by:
I have a windows client app that is trying to download a file from a web server but I always get the following error when I call the GetResponse method of the Request object. The remote server...
7
by: Miro | last post by:
Hi, ( using vb.net 2003 ) Im not quite sure what to look for in the help / online for this. Example: You have 2 seperate .exe files running ( both written in vb.net ) Is there a way to...
5
by: Ron | last post by:
I've got some C# code that sort of does what I want: Looking at the xml files in area: http://www.keepitsimplekid.com/xml I want to change Untitled Ad at the top of the xml to the name of the...
10
by: Stefan Weber | last post by:
Hi, I'm trying to access the JavaScript code contained in a <scripttag via its "text" attribute. This works well, if the code is embedded in the HTML page. However, when the code is in an...
1
by: Big Moxy | last post by:
Problem URL - http://projects.zanalysts.com/ariviewer/display.asp?ID=11 I'm using Access as the "database". I get this error in the above URL: ADODB.Fields error '800a0cc1' Item cannot be...
7
by: colin | last post by:
Hi, Is there a way of doing simple code generation inside visual c# express such as similar to preprocessing in c++ ? I need to generate a library for some vector maths, but I need to...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.