Passing arguments to Access Forms created with 

2019-07-03 11:06发布

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

2条回答
甜甜的少女心
2楼-- · 2019-07-03 11:31

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).

查看更多
Deceive 欺骗
3楼-- · 2019-07-03 11:34

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.

查看更多
登录 后发表回答