Run query in Access VBA and assign result to unbound text box on form
Posted on 2016-11-04
On an Access 2013 form, I need to run a query in a VBA event code and assign the result to an unbound textbox on the form.
Here’s the gist of what I’m doing…
We have a form whose Record Source is a table called CONTACT. As you might imagine, it displays Name, Title, etc., as well as OrgName. The event code I mentioned is a button click event that launches a macro that ultimately produces a sheet of address labels for the person whose record is being viewed on the form. All this works great! Unfortunately, some of the OrgNames are too long to fit on the labels, so we want to pull an abbreviated name (AltOrgName) from a different table called ORGANIZATION, and use that for the label-making feature.
I need a query that will select AltOrgName from ORGANIZATION, where ORGANIZATION.OrgName is the same as Me!OrgName, and then assigns that AltOrgName to the unbound textbox. The SQL would look like: SELECT ORGANIZATION.AltOrgName from ORGANIZATION where (ORGANIZATION.OrgName = Me!OrgName) -- but I just can’t figure out how to run it properly in the VBA code and assign it to the textbox.
A bit more info: The VBA event code pulls together Name, Title, etc. from several form fields and assembles this data into a hidden label textbox to base the label on. Thus, I need for the AltOrgName value to be assigned to its own form field (the unbound textbox, called txtAltOrgName) where the event code can find it, too. Then, as the event code is pulling data together, it will see if an AltOrgName is present before just using OrgName:
'Check for AltOrgName; will use it for label if there is one
If IsNull(Me.txtAltOrgName) Then
If IsNull(Me.OrgName) Then
var5 = ""
var5 = Me.OrgName & vbCrLf
var5 = Me.txtAltOrgName & vbCrLf
So my question again is, How do I run the query in VBA and how do I set the query result to Me.txtAltOrgName?
Thanks very much for the assistance.