Forum Discussion
Set default value in ComboBox from a SQL query
- Mar 23, 2022
Okay, then, I was not treating the default as a string, which it needs to be.
Try this, using DLookup and the string delimiters.
Private Sub Form_Load()Dim strUserName As String
strUserName = DLookup("name", "users", "username = " & fncUser() )
Me.YourComboBoxNameGoesHere.DefaultValue = """" & strUserName & """"
End Sub
Hi George_Hepworth , first of all thank you for your quick response.
I have a table that stores personal information. One of the fields is "User_reg" which is the user registered in Windows, another is the user's name. For example, a record can be ("Name and lastname", "username", ".....").
I have a query that returns a single value, which is the name of the person logged in Windows, the query being:
SELECT name FROM users Where username = fncUser().
I have developed a function that returns the registered username in Windows, and that is the one I use in the query:
Public Function fncUser() As String
fncUser = Environ("UserName")
End Function
The problem is that I have a form where I would like to automatically detect the logged in user and show his name in a Combobox as the default value.
If you have any questions about my project, please do not hesitate to contact me.
(sorry for my level of English, I hope everything is understood.)
Thank you. That's clear.
You can set the Default Value of a control in a couple of ways, either in VBA or in the property sheet.
This works using your function.
Note that the combo box in my example doesn't have a row source. I would anticipate that the row source in your combo box would be a list of potential users' usernames.
- markarelMar 23, 2022Brass Contributor
If, as you say, the combo box already has a list of users to select, what I would like to do is that depending on the user registered in Windows, it automatically selects the user's name.
In this list you select the name and surname of the user, if I put as default value "=fncUser()" it would write me the Windows user name, and what I need is that according to the registered Windows user name, it puts its name and surname.
Or what is the same, the result of this query:
SELECT name FROM users Where username = fncUser().
- George_HepworthMar 23, 2022Silver Contributor
Ah, sorry I missed that you wanted different values than the username.
I was going to suggest a different approach, but I'm getting the same error you reported!
I have to do some additional testing to see what I'm missing.
- George_HepworthMar 23, 2022Silver Contributor
Okay, then, I was not treating the default as a string, which it needs to be.
Try this, using DLookup and the string delimiters.
Private Sub Form_Load()Dim strUserName As String
strUserName = DLookup("name", "users", "username = " & fncUser() )
Me.YourComboBoxNameGoesHere.DefaultValue = """" & strUserName & """"
End Sub