简体   繁体   中英

MS Access: referring to a subform textbox control element in VBA query definition

I have a subform with user input (text box), that can reach more than 255 chars and can have special characters. As I cannot assign it as a parameter to a vba query definition (only 255 characters will work), I thought about directly referencing the text box:

Insert into ...
Values (Forms!MainFormName!txt_MyTextField, ... )

does work in a query in the Access GUI, but not in a vba query definition specified with the following code:

Set query_definition = CurrentDb.CreateQueryDef("", SQLQuery)) 

"Forms!MainFormName!NameOfSubformNavigationElement!txt_MyTextField" does not work either as a reference, just in case you are wondering. Neither does "Forms!MainFormName!NameOfSubformNavigationElement.Form.txt_MyTextField"

How can I get what I want? The string can have any kind of special chars like ' and ". Is there no alternative than appending the user input into the sql query? Is there some built-in function to escape these values?

UPDATE: Added another example now that the environment is known.

To use the form field in an action query, create a public function that will return the desired field, then call that function from your query.

Public Function GetFormField() As String
    GetFormField = Forms![MyMainForm]!MySub.Form.MyField
End Function

In your query, use something like:

WHERE ((([106thZip_code_database].zipcode)=GetFormField()));

The following is an example you could use in the Main form to reference a field in a subform. 'MySub' is the name of the control on the Main form - not the subform's object name.

Debug.Print Forms![MyMainForm]!MySub.Form.MyField

A good reference on this subject can be found at: http://access.mvps.org/access/forms/frm0031.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM