muncherelli
muncherelli

Reputation: 2903

Set Default Value of Text Box to Query Result

Fairly simple question. I have a text field in a form that I would like the default value to be set to the result of a query. This particular query returns a default tax rate for a small invoicing system I am setting up in Access.

The query (qrySettingsDefaultTaxRate) looks like this and returns one row with the decimal equivalent of the tax rate I would like to set as the default in this form:

SELECT CDbl([value]) AS default_tax_rate
FROM settings
WHERE (((settings.key_name)="default_tax_rate"));

I have tried setting the default value of my text field to:

=[qrySettingsDefaultTaxRate]![default_tax_rate]

However that didn't work. When I return to form view, the box comes up with "#Name?" as the default value instead of returning the result of the query.

Upvotes: 5

Views: 47075

Answers (4)

Robert
Robert

Reputation: 1631

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.

Upvotes: 1

Fionnuala
Fionnuala

Reputation: 91336

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.

Dlookup Default value

Upvotes: 4

dfasoro
dfasoro

Reputation: 241

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], """", """""") & """"

Upvotes: 2

Joby
Joby

Reputation: 41

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

Upvotes: 4

Related Questions