VBA Dlookup on a lookup wizard field - vba

I have two tables that are related, I'm trying to get data from the "parent" table using information in the "child" table. I'm attempting to use DLookup but I am getting a mismatch data type error.
I have a username variable available in the sub I am calling from and have created the below code:
Dim sqlstr As String
Dim placehldr As Long
username = Me.OpenArgs
placehldr = DLookup("userFullName", "tblUsers", "username='" & username & "'")
userFullName = DLookup("employeeFullName", "tblEmployees", "[ID]='&placehldr&'")
placehldr looks up according to a username the userFullName field which was created with lookup wizard so that users can look up the employee. This returns the autoID number from the first table tblEmployees. I have tried this using placehldr as long, integer, and string, and I have tried placing apostrophes as if it were a string or integer, I have also tried mixing these and using string apostrophes with int/long etc. It always returns the same mismatch type error on the second DLookup. Any help would be appreciated.

Dim sqlstr As String
Dim placehldr As Long
username = Me.OpenArgs
placehldr = DLookup("userFullName", "tblUsers", "username='" & username & "'")
userFullName = DLookup("employeeFullName", "tblEmployees", "[ID]=" & placehldr)
Per #dbmitch this worked correctly.

Related

MS Access Query to show Inventory Counts per Person (Using comma delimited)

I'm attempting to setup a query that will show how many of each ship is owned and who owns it displaying each "Call Sign" who owns the ship in comma delimited format.
The table being used for the query is called "Members" and I'm using a Count function on the "Current Ships Owned" field in the query to get count totals.
The Base query is the following:
I used VBA to build the following module:
Public Function QueryFieldAsSeparatedString(ByVal fieldName As String, _
ByVal tableOrQueryName As String, _
Optional ByVal criteria As String = "", _
Optional ByVal sortBy As String = "", _
Optional ByVal delimiter As String = ", " _
) As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sql As String
Dim whereCondition As String
Dim sortExpression As String
Dim retVal As String
Set db = CurrentDb
If Len(criteria) > 0 Then
whereCondition = " WHERE " & criteria
End If
If Len(sortBy) > 0 Then
sortExpression = " ORDER BY " & sortBy
End If
sql = "SELECT " & fieldName & " FROM " & "Members" & whereCondition & sortExpression
Set rs = db.OpenRecordset(sql, dbOpenForwardOnly, dbReadOnly)
Do Until rs.EOF
If Not IsNull(rs.Fields(0).Value) Then
retVal = retVal & Nz(rs.Fields(0).Value, "") & delimiter
End If
rs.MoveNext
Loop
retVal = Left(retVal, Len(retVal) - Len(delimiter))
QueryFieldAsSeparatedString = retVal
rs.Close
Set rs = Nothing
Set db = Nothing
End Function
I then added the field with the owners by adding the following expression to my query:
Owners: QueryFieldAsSeparatedString("[Call Sign]","Members",Count([Members]![Current Ships Owned])>=1)
But it comes back with the error "Your query does not include the specified expression 'Owners' as part of an aggregate function". Changing it from expression to group by gives an error "reserved error (-3087);"
If I remove the Count from the expression it runs but gives me all members rather than the members that own the ships.
Any help or push in the right direction would be greatly appreciated. I'm not sure what I'm missing but I think some fresh eyes on the issue may help.
Thank you!!
-Deke
Note that you have basically replicated http://allenbrowne.com/func-concat.html
The criteria parameter is the problem. It expects a string, but you pass an expression.
And even if Access silently converts it, WHERE Count([field]) >= 1 is not valid in the WHERE clause, that would only work in a HAVING clause.
But what you actually need there is a criterium that collects all Members records that belong to the current query record.
See the usage example on Allen Browne's page, and the documentation of the strWhere parameter.

MS Access - UPDATE SQL Query Error 3061

I try to update data in a table with text delivered from a InputBox.
Private Sub editname_Click()
Dim GivenNameTB As String
Dim EnterName As String
Dim SQl As String
Dim LocationID As Integer
Me.txt_name.SetFocus
GivenNameTB = Me.txt_name.Text
EnterName = InputBox("Change name", "Change name", GivenNameTB)
LocationID = Me.list_ma.Column(1)
SQl = " Update tWorkers SET GivenName = forms!mainform!EnterName WHERE tWorkers.IDName = forms!mainform!LocationID "
CurrentDb.Execute SQl
End Sub
However, I get error code 3061 "Too few parameters. Expected 2"
EDIT:
The table structure of tWorkers:
IDName - auto-increment (primary key)
LastName - text
GivenName - text
I'm targeting column GivenName by SET GivenName = ..., and the row by LocationID.
LocationID gets its value from the list field list_ma. The list field consists of five columns whereas IDName is column 2.
My whole point is to update a field in a table. A text box in my form shows a name which can be edited by clicking a button. Then a inputbox pops up. The entered string should be saved in the desired field.
Re-reading your question, your data lives in VBA variables, not in form controls. So you can't read the parameters from the form (DoCmd.RunSQL won't help).
You must construct the SQL string dynamically, best using CSql() by Gustav :
SQL = "Update tWorkers SET GivenName = " & CSql(EnterName) & _
" WHERE tWorkers.IDName = " & CSql(LocationID)
Debug.Print SQL
CurrentDb.Execute SQL
I think you need DoCmd.RunSQL rather than CurrentDb.Execute.
Private Sub editname_Click()
Dim GivenNameTB As String
Dim EnterName As String
Dim SQl As String
Dim LocationID As Integer
Me.txt_name.SetFocus
GivenNameTB = Me.txt_name.Text
EnterName = InputBox("Change name", "Change name", GivenNameTB)
LocationID = Me.list_ma.Column(1)
SQL = " Update tWorkers SET GName = " & chr(34) & EnterName & chr(34) & " WHERE tWorkers.IDName = " & LocationID
Debug.Print SQL -- For checking what code we are running.
DoCmd.RunSQL SQL
End Sub

Placing a Query Result in A String Variable

Was wondering how can we put an SQL statement in a String Variable?
Example:
Dim sqlQuery as String, qHolder as String
sqlQuery = "SELECT ID.table from table WHERE ID ='" userInputTextBox "'"
Whenever i do the above statement using either OpernRecordset() or RecordSource it gives me a bug. Can you give an example on how we do this, so we can use the value of sqlQuery for comparison for example
if(sqlQuery = userInputTextBox)then
MSgBox(" Match Found " )
Else
MsgBox("No Match Found")
Big Thanks in Advance.
Use the string concatenation operator (&).
sqlQuery = "SELECT ID.table from table WHERE ID ='" & userInputTextBox & "'"
Otherwise, it's a syntax error.
UPDATE
To get the value of ID.table into a string, use the Fields property of the Recordset:
Dim s As String
' by index
s = MyRec.Fields(0)
' or by name
s = MyRec.Fields("ID.table")

Update in new column after inserting into 2 columns in a db

I am using following code to insert records into a table from another table....
Private Sub InsDuplicateDB()
Dim strInsDup As String = "INSERT INTO Duplicate_srno(Sr_no,chalan_no) SELECT sr_no,chaln_no FROM Vendor_Machine where sr_no=#srno"
Dim comm_InsDup As OleDb.OleDbCommand = New OleDb.OleDbCommand(strInsDup, cnnOLEDB)
comm_InsDup.Parameters.AddWithValue("#srno", cmbSn_no.Text)
comm_InsDup.ExecuteNonQuery()
Dim strUpdDup As String = "UPDATE Duplicate_srno SET sr_no = #srno,chaln_no =#chn_no,Problem=#problemWHERE sr_no = #srno AND chalan_no=#chn_no"
Dim comm_Update As OleDb.OleDbCommand = New OleDb.OleDbCommand(strUpdDup, cnnOLEDB)
comm_Update.Parameters.AddWithValue("#srno", cmbSn_no.Text)
comm_Update.Parameters.AddWithValue("#chn_no", cmbChal_no.Text)
comm_Update.Parameters.AddWithValue("#problem",strProb)
comm_Update.ExecuteNonQuery()
End Sub
Here strProb is a string whose value is assigned in anoter sub function..
Here it gives error as "No values given for one or more required parameter.."
Please resolve my problem
I don't know if this is a typo or not, but the update string lacks of a space between the parameter name #problem and the WHERE clause
Dim strUpdDup As String = "UPDATE Duplicate_srno SET sr_no = #srno,chaln_no =#chn_no," & _
"Problem=#problem WHERE sr_no = #srno AND chalan_no=#chn_no"
^
However the update string could be simplified because you are updating two fields with the same values used in the where clause
Dim strUpdDup As String = "UPDATE Duplicate_srno SET Problem=#problem " & _
"WHERE sr_no = #srno AND chalan_no=#chn_no"
Apart from the missing space the error message says that the engine expects more parameters.
In OleDb the parameters are not recognized by their name. You need the same number of parameter that are defined by the placeholders in the string. In your original text, you have 5 placeholders but you add only 3 parameters. It doesn't matter if two of them are the same.
The revised code coould be the following
Dim strUpdDup As String = "UPDATE Duplicate_srno SET Problem=#problem " & _
"WHERE sr_no = #srno AND chalan_no=#chn_no"
Dim comm_Update As OleDb.OleDbCommand = New OleDb.OleDbCommand(strUpdDup, cnnOLEDB)
comm_Update.Parameters.AddWithValue("#problem",strProb)
comm_Update.Parameters.AddWithValue("#srno", cmbSn_no.Text)
comm_Update.Parameters.AddWithValue("#chn_no", cmbChal_no.Text)
Notice how I have added the #problem parameter as first in the collection. Now, the parameter collection is in the same order in which the placeholders are present in the command text.

Microsoft Access can't find the field '|1'

I keep getting a run time error '2465' when running a query via VBA in Access.
Error: Microsoft Access can't find the field '|1' referred to in your expression
I can't seem to find where this issue is occuring. Below is the VBA code that I'm currently using to requery a form.
Dim Test As String
Test = "*" & Combo161.Value
Dim strSQL As String
Dim strWhere As String
strWhere = (Chr(34) + Test + (Chr(34)))
'MsgBox (strWhere)
strSQL = "SELECT * FROM Test_Query WHERE TestID " & strWhere
'MsgBox (strSQL)
[Form_Test (subform)].RecordSource = strSQL
[Form_Test (subform)].Requery
The TestID had a field formatting of text, rather than a number. Does this matter at all?
I have just fixed this error. I was referencing the subform's source object, rather than its name given in the form properties.
I had the same error. What I missing was the double quotes around a string. This error is a bit misleading. Check the syntax etc and you will find the issue was related to comma or double quotes etc.
Try:
Dim Test As String
Test = "*" & Combo161.Value
Dim strSQL As String
Dim strWhere As String
strWhere = (Chr(34) & Test & (Chr(34)))
'MsgBox (strWhere)
strSQL = "SELECT * FROM Test_Query WHERE TestID Like " & strWhere
'To test
'Debug.print strSQL
If this is a subform, then:
Me.[Form_Test (subform)].Form.RecordSource = strSQL
''Not needed when changing record source
''Me.[Form_Test (subform)].Form.Requery
You did not have an equals sign / Like and the concatenator in VBA is &, not +, using + can lead to problems with nulls, but in this case, I reckon the problen is the missing Like, that is
TestID Like "*something"
You can control the contents of a subform with a combo and a link field: