Set Default Value of Text Box to Query Result

孤人 提交于 2019-12-05 09:59:36
Fionnuala

You can set the control source of a textbox to DLookup, or set the value to DLookup in code.

DlookUp("default_tax_rate","qrySettingsDefaultTaxRate")

Or

DlookUp("default_tax_rate","settings","settings.key_name='default_tax_rate'") 

You can even put DLookUp on the property sheet under Default Value.

I had a similar problem. This is what worked for me - I wrote a function that returned the value I wanted to set as default and specified the function in the default of the form.

My code:

Public Function MaxTDate()
    MaxTDate = CurrentDb.OpenRecordset("MaxTDateQry").Fields(0)
End Function

...and in the field properties:

Default Value =MaxTDate()

Even though the answer now ticked as the right answer suffices for some instances.

There might be instances when the default value comes from an expression, an external file, user input or some other computation whatsoever.

The reason why Microsoft Access throws a #Name? error is because it expects String data to be quoted with apostrophes ". While also saying that, If the string itself contains an apostrophe, it needs to be escaped as well. Think addslashes in php.

So giving a particular variable DefValue,

Dim DefValue
DefValue = "This is a static string or result from database query or other computation"
TextBox.DefaultValue = """" & Replace(DefValue, """", """""") & """"

So, in your case, it will be """" & Replace([qrySettingsDefaultTaxRate]![default_tax_rate], """", """""") & """"

The answer by Fionnuala contains an error in the second part. Unfortunately my edit got rejected twice, so now I post it as a separate reply. It needs to be as:

DLookUp("value","settings","settings.key_name='default_tax_rate'") 

The reason is that in the original Table settings the column is called value, while default_tax_rate is only created in the query qrySettingsDefaultTaxRate which is based on settings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!