Passing arguments to Access Forms created with 'New' - forms

I have a form called 'detail' which shows a detailed view of a selected record. The record is selected from a different form called 'search'. Because I want to be able to open multiple instances of 'detail', each showing details of a different record, I used the following code:
Public detailCollection As New Collection
Function openDetail(patID As Integer, pName As String)
'Purpose: Open an independent instance of form
Dim frm As Form
Debug.Print "ID: " & patID
'Open a new instance, show it, and set a caption.
Set frm = New Form_detail
frm.Visible = True
frm.Caption = pName
detailCollection.Add Item:=frm, Key:=CStr(frm.Hwnd)
Set frm = Nothing
End Function
PatID is the Primary Key of the record I wish to show in this new instance of 'detail.' The debug print line prints out the correct PatID, so i have it available. How do I pass it to this new instance of the form?
I tried to set the OpenArgs of the new form, but I get an error stating that OpenArgs is read only. After researching, OpenArgs can only be set by DoCmd (which won't work, because then I don't get independent instances of the form). I can find no documentation on the allowable parameters when creating a Form object. Apparently, Microsoft doesn't consider a Constructor to be a Method, at least according to the docs. How should I handle this? (plz don't tell me to set it to an invisible text box or something) Thanks guys, you guys are the best on the net at answering these questions for me. I love you all!
Source Code for the multi-instance form taken from: http://allenbrowne.com/ser-35.html

Inside your Form_detail, create a custom property.
Private mItemId As Long
Property Let ItemID(value as Long)
mItemId = value
' some code to re query Me
End Property
Property Get ItemId() As Long
ItemId = mItemId
End Property
Then, in the code that creates the form, you can do this.
Set frm = New Form_detail
frm.ItemId = patId
frm.Visible = True
frm.Caption = pName
This will allow you to pass an ID to the new form instance, and ensure it gets requeried before making it visible. No need to load all of the results every time if you're always opening the form by Newing it. You let the property load the data instead of the traditional Form_Load event.
This works because Access Form modules are nothing more than glorified classes. Hope this helps.

You could try applying a filter:
frm.Filter = "[ID] = " & patID
frm.FilterOn = True
The Record Source of the Detail form will need to be set to the table to which the ID belongs.
UPDATE
As you requested, here is the code to set the RecordSource:
frm.RecordSource = "select * from TableName where [ID] = " & patID
This is probably cleaner than using a filter given that a user can remove the filter (depending on the type of form).

Related

MS Access Multiple Instances of Single Form for different clients

Another question that stumps me.
I have a continuous form that shows a list of all of our clients at the law firm I work at here. Right now you can double click on a client name where a form (frmContactSummary) then opens up to display all the information for that client.
Problem is, as it is currently designed only one form can be open for a client at a time.
We want to be able to open multiple versions or instances of frmContactSummary.
I borrowed code from Allen Browne's site, which is as follows:
Option Compare Database
Option Explicit
'Author: Allen J Browne, July 2004
'Email: allen#allenbrowne.com
'Found at: http://allenbrowne.com/ser-35.html
Public clnClient As New Collection 'Instances of frmClient.
Function OpenAClient() 'ContactID As Integer
'Purpose: Open an independent instance of form frmClient.
Dim frm As Form
'Debug.Print "ID: " & ID
'Open a new instance, show it, and set a caption.
Set frm = New Form_frmContactSummary
frm.Visible = True
frm.Caption = frm.Hwnd & ", opened " & Now()
'Append it to our collection.
clnClient.Add Item:=frm, Key:=CStr(frm.Hwnd)
Set frm = Nothing
End Function
This works in a way, but it only opens up the first record in our Contact table. We want the instance to open on a specific record, or ID from the Contacts table.
I tried this code near the end:
frm.RecordSource = "select * from Contacts where [ID] = " & ContactID
But it did not work.. :-(
Any advise would be much appreciated! Thank you!
Ok, when you create a instance of a form, you can’t use the common approach of a where clause like this:
Docmd.OpenForm "frmContactSummary",,,"id = " & me!id
The above of course would work for opening one form.
However, in your case, you need:
Create a new instance of the form
Move/set the form recordsource to ID
Display the form
So we need a means to move or set the form to the ID of the row we just clicked on.
So right after we create the form, then add this line of code:
Set frm = New Form_frmContactSummary
Frm.RecordSource = "select * from Contacts where id = " & me!id
And rest of your code follows.
It not clear if the PK (key) of the table Contacts is “id”, or “ContactID”
So your code will be:
Frm.RecordSource = "select * from Contacts where id = " & me!id
Or
Frm.RecordSource = "select * from Contacts where Contactid = " & me!ContactID
Simply replace “ContactID” in above with a actual PK id used in table contacts. The "Id" has nothing to do with the collection. We are simply building a SQL statement that will pull/set the form to the one row. So the only information required here is what is the PK name in your continues form, and what is the PK name in your frmContactsSummary. (they will be the same name in both forms, and should thus be the same in the sql statement.

Error 1004 - Vlookup in vba - Unable to get the Vlookup property of the WorksheetFunction class

I've browsed the various questions already asked with this issue other users have faced and none of the solutions seem to fix the error code coming up.
I have a form which prompts the user for a reference number - they input this into the text field and then press OK
'OK button from form1
Public Sub CommandButton1_Click()
refInput = refTextBox.Value
InputRef.Hide
ExportShipForm.Show
End Sub
Once this has been pressed, the next form appears which I would like to be populated with data based on the reference number input on the first form. I have an update button which will update the "labels" on the form to show the data - this is where I am getting an error.
The first label to update is through a Vlookup:
Below the users clicks the update button the 2nd form:
Public Sub btnUpdate_Click()
Call ICS_Caption
lbl_ICS.Caption = Label_ICS
End Sub
This calls a function below:
Public Sub ICS_Caption()
Dim ws1 As Worksheet
refInput = InputRef.refTextBox.Value
Set ws1 = Worksheets("MACRO")
dataRef = Worksheets("Shipping Data").Range("A:K")
Label_ICS = WorksheetFunction.VLookup(refInput, dataRef, 7, False)
End Sub
The error continues to come up each time - I have ran the vlookup manually in a cell outside of VBA and it works fine.
I have typed the range in the Vlookup whilst also using named ranges but each variation shows the same error.
Eventually, I would want the label on form 2 to update with the result of the Vlookup.
Any ideas?
You need to Dim dataRef as Range and then Set it.
See code Below:
Dim DataRef as Range
Set dataRef = Worksheets("Shipping Data").Range("A:K")
Just like a Workbook or Worksheet you need to Set the Range
Just as Grade 'Eh' Bacon suggest in comments its always best to Dim every reference.
The best way to do so is to put Option Explicit all the way at the top of your code. This forces you to define everything which helps it preventing mistakes/typo's etc.
Update edit:
The problem was you are looking for a Reference number in your Sheet (thus an Integer) but refInput is set as a String this conflicts and .VLookup throws an error because it can't find a match.
I have reworked your code:
Your sub is now a function which returns the .Caption String
Function ICS_Caption(refInput As Integer)
Dim dataRef As Range
Set dataRef = Worksheets("Shipping Data").Range("A:K")
ICS_Caption = WorksheetFunction.VLookup(refInput, dataRef, 7, False)
End Function
The update Button calls your Function and provides the data:
Public Sub btnUpdate_Click()
lbl_ICS.Caption = ICS_Caption(InputRef.refTextBox.Value)
End Sub
By using a Function you can provide the Integer value and get a return value back without the need of having Global Strings or Integers.
Which would have been your next obstacle as you can only transfer Variables between Modules/Userforms by using a Global Variable.
I would even advice to directly use the function in the Initialize Event of your 2nd Userform to load the data before the Userform shows this is more user friendly then needing to provide data and then still needing to push an update button.
Verify that you have no missing libraries in VBA IDE > Tools > References
Try using a worksheet cell as the place to store and retrieve refTextBox.Value, rather than refInput (which I assume is a global variable):
Public Sub CommandButton1_Click()
...
Worksheets("Shipping Data").Range($M$1).Value=refTextBox.Value
End Sub
Public Sub ICS_Caption()
Dim refInput as Long'My assumption
...
refInput=Worksheets("Shipping Data").Range($M$1).Value
...
End Sub
Make sure you have Option Explicit at the top of all of your code windows.

Utilizing Access and VBA: copying information between forms

Searched around a bit and could not find an existing post with my exact question.
I am creating an Access (2003) database utilizing multiple forms and tables that need to communicate and share information with one another (i.e. - first/last name, etc.). The main form/table, "Personnel", will hold a majority of the information, yet the other forms/tables will only hold information pertinent to certain situations/circumstances, so not every entry in "Personnel" will have a concurrent entry in "Hired", for example. If a record with the same name already exists, I would like a MsgBox to tell me so and open that entry (in the form, for editing), if not a new entry would be created, auto-populated with pre-selected fields (i.e. - first/last name).
After an option is selected from a pull-down menu, the appropriate form is accessed/opened, "Hired", for example (This part works).
The copying information across forms does not work.
Dim rstPers, rstHired As DAO.recordset
Dim LastName As String
If status = "hired" Then
DoCmd.OpenForm "Hired Information"
Set rstPers Forms!Personnel.RecordsetClone
Set rstHired Forms![Hired Information].RecordsetClone
????
...
End If
I have tried to do this multiple ways but nothing seems to work. Nothing populates in the new Form or table. Am I looking at it the wrong way? Should I try a different approach?
Hope my explanation makes sense. Thanks for any help.
-Charles
You have a bad approach indeed.
Your forms are linked to a table. So you should avoid as much as possible to manipulate or retrieve a form's data directly using a recordsetclone, instead try to retrieve this data directly from the table.
So if you want to open your "hired information" form:
Dim RS As Recordset
Dim IDperson As String
IDperson = me.ID ' or whatever
Set RS = CurrentDb.OpenRecordset("SELECT ID FROM TableHired WHERE ID='" & IDperson & "'")
If RS.BOF Then
' No record exist - Open form in record creation
DoCmd.OpenForm "FormHired", acNormal, , , acFormAdd
Else
' record exists, open form and position it oon the record's ID
DoCmd.OpenForm "FormHired", acNormal, , "ID='" & RS!ID & "'", acFormEdit
End If
Of course it won't work like this as you didn't provide enough info.
Review this code and adapt it with your fields name (IDs), table name (TableHired) and FormName (FormHired) and following the situation on where and how you will trigger it. Also if your ID is not a string, you should remove the quotes in the SQL

Access 2010 Trying to Enter a unique record through Form

I'm trying to input an error check for my form. I have the user entering the name and I would like a prompt to inform them if they are attempting to use a Name already in the records.
Example: the Person table has 3 records with FNames being: Jeff, Kyle, Darren.
If on the add person form in the Fname Box Kyle is entered, the after update event will notify the user that this name has been claimed and null the field. Where as if Greg was enter no notifications will occur.
I just don't know how to compare a text field value to values in a filtered query list, and Google searches have other loosely related links in the way.
Thank you for help!
If all fnames must be unique, add a unique index to the table. This will prevent duplicates being entered. The form error property will allow you to provide a custom error.
You can also check if the name exists in the Before Update event of the control.
In this example, the control and field are both called AText. Generally, you should rename controls so they are not the same as fields.
Private Sub AText_BeforeUpdate(Cancel As Integer)
Dim IsOk As Boolean
''One of the very few places where the .Text property is used
sLookUp = Me.AText.Text
IsOk = IsNull(DLookup("Atext", "Table1", "Atext='" & sLookUp & "'"))
If Not IsOk Then
MsgBox "Found!"
Cancel = True
End If
End Sub

MS Access implenting hyperlink like behavior for records to switch between forms

I'm currently working on a Database which requires the following functionality:
For example given a specific project, I have a series of structures which belong to that project, which are displayed in a datasheet view on the project form. I am attempting to allow the user to on double click to navigate to that specific structure which is displayed on another form. Currently I am using filters to implement this behavior, however, this results in the filter being left on, and when I manually turn off the filter, the form I switch to returns back to the first entry.
I am using the current code on the datasheet:
Private Sub struct_name_DblClick(Cancel As Integer)
LookupValue = Me.struct_ID
Form_frm_control.pg_structure.SetFocus
Form_frm_control.subform_structure.Form.Filter = "struct_ID = " & LookupValue
Form_frm_control.subform_structure.Form.FilterOn = True
End Sub
Any help would be greatly appreciated. Thanks in advance.
It all depends on what you need to do.
If you want to display all records and navigate to the selected record, then you can use bookmark navigation:
With Forms!MyOtherForm
.RecordsetClone.FindFirst "struct_ID = " & Me!struct_ID
If Not .RecordsetClone.NoMatch Then
If .Dirty Then
.Dirty = False
End If
.Bookmark = .RecordsetClone.Bookmark
End If
End With
This assumes that the other form is open with all the records loaded.
Another approach to this problem, which I find more useful for popup situations like this, is to just open the other form as a dialog and require it be closed before returning to the calling context. In that case, you'd do this:
DoCmd.OpenForm "MyOtherForm", , , "struct_ID = " & Me!struct_ID, , acDialog
You'd then have to close the other form to get back to the original context.
You might think that with large numbers of records this would be inefficient, but it's actually very fast, as this operation is highly optimized within Access (moreso than filtering an already open form, in fact).