MS Access DLOOKUP with text and nested DLOOKUP for criteria - ms-access

I have a combobox on a form that contains search terms. The user chooses a search term and this looks up to a table containing the number X. The RVU (a number) of X is looked up in another table given the category is equal to the string 'PHYS'. I was using nested DLOOKUP statements to look up the number X and then use that number X and the string criteria to look up the RVU. Here's my code:
FH_array(0) = Val(Nz(DLookup("[RVU]", "[FORES IP Picker]", "[IP]= " & Val(Nz(DLookup("[FORES]", "[IP Number Xwalk]", "[Reference Name] = '" & Me.Ref_Name & "'"), 0))), ""))
I wasn't having luck so I broke it down to debug:
a = Val(Nz(DLookup("[FORES]", "[IP Number Xwalk]", "[Reference Name] = '" & Me.Ref_Name & "'"), 0))
Debug.Print "a:"; a 'returns value 279
aa = Val(nz(DLookup("[RVU]", "[FORES IP Picker]", "[IP] = " & a & " and [Cost Category] = 'PHYS')))
Debug.Print "aa:"; aa
I'm getting a syntax error on the line for variable aa. if I changed the code from
aa = DLookup("[RVU]", "[FORES IP Picker]", "[IP] = " & a & " and [Cost Category] = 'PHYS')
to
aa = DLookup("[RVU]", "[FORES IP Picker]", "[Cost Category] = 'PHYS'" And "[IP] = " & a)
I get a run-time error 13 type mismatch
All the variables are declared as variant and called properly. The array FH_array is sized correctly. I copied this code from another database that does the same type of nested DLOOKUP but it has only one criteria and therefore works. I can't figure out what syntax I'm missing or where the type mismatch is to get it to work.

You need a single valid string as the DLookup criteria option. Use the Immediate window to examine what you have for the criteria in the final DLookup example.
Debug.Print "[Cost Category] = 'PHYS'" And "[IP] = " & a
That is actually a "logical conjunction" of two strings. (That will make more sense if you review the Access help topic for the And Operator.)
And since you're using And with two string expressions, Access complains about type mismatch, the same as it does with this simpler example:
Debug.Print "a" And "b"
So you need to create a single valid string for the criteria option ...
a = 279
Debug.Print "[Cost Category] = 'PHYS' And [IP] = " & a
[Cost Category] = 'PHYS' And [IP] = 279
Translating that back to the last DLookup in your question ...
Dim strCriteria As String
strCriteria = "[Cost Category] = 'PHYS' And [IP] = " & a
Debug.Print strCriteria ' <- just to make sure you got what you need
aa = DLookup("[RVU]", "[FORES IP Picker]", strCriteria)

Related

What is the DLookup and Nz() format for when field in table is Null?

I have a DLookup formula that fetches the [Model] from MyTable. Everything works until the value for fieldname [Model] is blank.
I get a Runtime Error 94 about how it doesn't understand null information.
I have tried using Nz() function. It is confusing to use these functions when I have so many double and single quotes.
This is what I have.
Dim other as String
other = DLookup("[Model]", "[Part Number & Part Name]", "[Part Number]='" & Forms![Press 2]![Containment - Press 2 subform].Form![Part Number] & "'")
If other <> "" Then
Me.[Model].Value = other
Else
Me.Model.Value = "NA"
End If
Use Nz and reduce the code:
Dim other as String
other = Nz(DLookup("[Model]", "[Part Number & Part Name]", "[Part Number]='" & Forms![Press 2]![Containment - Press 2 subform].Form![Part Number] & "'"), "NA")
Me![Model].Value = other
There are two tricky places for null values in your code:
If Forms![Press 2]![Containment - Press 2 subform].Form![Part Number] is null, the DLookUp will be processed incorrectly, since you're including it as a string.
Fix: use the form value as a parameter, this also avoids SQL injection errors:
other = DLookup("[Model]", "[Part Number & Part Name]", "[Part Number]= Forms![Press 2]![Containment - Press 2 subform].Form![Part Number]")
You're storing the DLookUp result in a string. You can either use Nz here to return a different string, or concatenate a zero-lenght string with the DLookUp result to process a Null value as a zero-length string:
other = VbNullString & DLookup("[Model]", "[Part Number & Part Name]", "[Part Number]= Forms![Press 2]![Containment - Press 2 subform].Form![Part Number]")
That should cover all places where nulls can interfere with this part of code.

Issue with DLookup when comparing strings in Query

I am trying to use Dlookup to look up a value in a query using two criteria ("s" and "Error") to populate variable "SCount". s is an integer for shift number, and Error is a string. Both are fields in the query. The Dlookup is pulling from a query which should be strings for the data type, the query is pulling from a table where the fields are strings. So I am not sure why I am getting a mismatch error.
When I run the code I get the error "Run-time error '3464' Data type mismatch in criteria or expression". For the the Error in the SCount Dlookup.
Code
Dim Error As String
Dim i As Integer
Dim s As Integer
Dim n As Integer
Dim SCount As Variant
Dim sum As Double
sum = 0
i = 1
s = 1
n = 1
Do Until i > 5
If Not IsNull(DLookup("[Type of Error]", "RankedSumOfErrors", "[Ranking] = " & i)) Then
Error = DLookup("[Type of Error]", "RankedSumOfErrors", "[Ranking] = " & i)
Me.Controls("lbl" & i & "").Caption = Error
Do Until s > 3
SCount = DLookup("[SumOfNumber of Errors]", "ErrorsByShift", "[Shift] = " & s & " AND [Type of Error] = '" & Error & "'")
Me.Controls("lbls" & s & "").Caption = SCount
i = i + 1
sum = sum + SCount
Loop
Me.Controls("Total" & i & "").Caption = sum
sum = 0
Else
Me.Controls("lbl" & i & "").Caption = "N/A"
i = i + 1
End If
Loop
If the fields are strings in the query, they should be so as well in the DLookUp.
Add parentheses to your DLookUp to avoid the error:
SCount = DLookup("[SumOfNumber of Errors]", "ErrorsByShift", "[Shift] = '" & s & "' AND [Type of Error] = '" & Error & "'")

Use text from record to paste into an Access form controlbox

Based on a user's job ID number, I create a recordset of an ID with its different unit types (think pipe sizes) and unit (think footage of pipe). Each unit type record already has the name of the form textbox where the total footage goes in a different column. What I want to do is go through each recordset and plugin the footage for each unit type for that job ID number (that the user puts in a form).
Dim rst_UnitEntryCounts As Recordset
Set rst_UnitEntryCounts = CurrentDb.OpenRecordset("SELECT tbl_UnitTypes.UnitTypes_WeeklyTextBoxUserEntryForm, " _
& " tbl_PMEntry.PMEntry_Week_Ending, " _
& " tbl_UnitTypes.UnitTypes_CumalativeTextBoxUserEntryForm, " _
& " Sum(tbl_UnitEntry.UnitEntry_Unit_Count) AS SumOfUnitEntry_Unit_Count " _
& "FROM tbl_UnitTypes " _
& " INNER JOIN tbl_UnitEntry ON tbl_UnitTypes.UnitTypes_ID = tbl_UnitEntry.UnitEntry_UnitTypes_ID) " _
& " INNER JOIN (tbl_PMHeader " _
& " INNER JOIN tbl_PMEntry ON tbl_PMHeader.PMHeader_ID = tbl_PMEntry.PMEntry_PMHeader_ID) ON tbl_UnitEntry.UnitEntry_PMEntry_ID = tbl_PMEntry.PMEntry_PMHeader_ID " _
& "WHERE tbl_PMHeader.PMHeader_ID = " & num_PM _
& "GROUP BY tbl_UnitTypes.UnitTypes_WeeklyTextBoxUserEntryForm, " _
& " tbl_PMEntry.PMEntry_Week_Ending, " _
& " tbl_UnitTypes.UnitTypes_CumalativeTextBoxUserEntryForm ")
rst_UnitEntryCounts.MoveFirst
Do Until rst_UnitEntryCounts.EOF = True
[rst_UnitEntryCounts.UnitTypes_WeeklyTextBoxUserEntryForm] = SumOfUnitEntry_Unit_Count
rst_UnitEntryCounts.MoveNext
Loop
Exit Sub
image of what my query table looks like
Also, Im getting an error 3131 Syntax error in FROM clause as well.
Thanks in advance!
Finally figured out how to "place" a value (sum of units) in a textbox that varies based on criteria (unit type) in a form, where the name of the textbox is inside a record itself within my recordset. In case someone else has a similar question, here is how I did it:
Dim cntl As String
Dim frm As String
Dim rst_UnitEntry As Recordset
frm = "frm_UserEntry"
Set rst_UnitEntryCounts = CurrentDb.OpenRecordset("SELECT...)
If rst_UnitEntryCounts.RecordCount <> 0 Then
rst_UnitEntryCounts.MoveFirst
Do Until rst_UnitEntryCounts.EOF = True
If rst_UnitEntryCounts![UnitTypes_CumalativeTextBoxUserEntryForm] <> "" Then
cntl = rst_UnitEntryCounts![UnitTypes_CumalativeTextBoxUserEntryForm]
Forms(frm).Controls(cntl) = rst_UnitEntryCounts![SumOfUnitEntry_Unit_Count]
End If
rst_UnitEntryCounts.MoveNext
Loop

Using array in WHERE clause of SQL statement using access VBA

I have an array ListBoxContents(), it will contain the items like '15', '16','25'..upto 10 items. I'm trying to retrieve data in the column Bnumber where data of length >6 and starting with('15', '16','25'...) i.e those items specified in listbox .And trying to query these listbox items in where cluase of the sql statement
Table column Bnumber contains
Bnumber
152
156
1523
16417
AA454
CC654
18A16
1826
18A16
25A76
54A16
54235A68
My VBA code
Private Sub arraywhere()
Dim qry As String
Dim Size As Integer
Size = Form_Input_From.lstdigits.ListCount - 1
ReDim ListBoxContents(0 To Size) As String
ReDim LContents(0 To 30) As String
Dim m As Integer
For m = 0 To Size
ListBoxContents(m) = Form_Input_From.lstdigits.ItemData(m)
Next m
For m = 0 To Size
qry = "SELECT col1,col2,Bnumber " & _
"FROM table WHERE (Len([table].[Bnumber]))>6) AND (Left
([table].[Bnumber],2))=(" & ListBoxContents(m) & ");"
Next m
Debug.Print qry
Application.CurrentDb.QueryDefs("[arrayqry]").sql = qry
DoCmd.OpenQuery "[arrayqry]"
End Sub
But my WHERE clause reads only last array item only. How do i specify array in where clause?
Try something like
" ... ([table].[Bnumber],2)) in ('" & Join(ListBoxContents,"','") & "');"
You are setting qry to a new statement with each iteration of your for loop. Instead you need to concatenate a string based on your list box contents that will look like ("x", "y", "z") and replace = with in.
Finish by setting your query once it will look similar to this:
qry = "SELECT col1,col2,Bnumber " & _
"FROM table WHERE (Len([table].[Bnumber]))>6) AND (Left
([table].[Bnumber],2)) in (" & commaSeperatedContents & ");"
Where commaSeperatedContents is a String that is like ("x", "y", "z") but of course has your values.
Try this one:
Dim inPart As String
For m = 0 To Size
inPart = inPart & "'" & ListBoxContents(m) & "',"
Next m
inPart = Left(inPart, Len(inPart) - 1)
qry = "SELECT col1,col2,Bnumber " & _
"FROM [table] WHERE Len([table].[Bnumber])>6 AND " & _
"Left([table].[Bnumber],2) In (" & inPart & ");"
Debug.Print qry
CurrentDb.QueryDefs("[arrayqry]").SQL = qry
DoCmd.OpenQuery "arrayqry"
The list of items in your array actually seems to be coming from the Form_Import_From_PMT.lstdigits control. Is this control bound to a data source? If so, you can simply join your table to that data source with a join clause that specifies that only rows with Bnumber values starting with the digits in the joined table are to be selected:
select col1, col2, Bnumber
from table as t
inner join tblDigits as d
on left(t.Bnumber, 2) = d.Digits
where len(t.Bnumber) > 6
If the control is not bound to a data source, then bind it now (creating a new table tblDigits to hold the digits, as shown above), and you'll be able to use the above query.
In short, data binding is how you 'use an array in a where clause' in Access.

Access VBA: DLookUp function giving type mismatch error

I'm trying to run the following code, but I'm getting a "Type mismatch" compile error on DLookUp.
DLookUp returns a value, right?
This code, to me, says: in the strSQL recordset, look for where the SKUS_ORDERED column equals curSKU2.
strSQL, temp, curSKU2 are all initialized as string type variables.
...
strSQL = "SELECT * FROM ORDER_DATA WHERE [ORDER]=" & curOrder
Dim temp As String
temp = DLookup("SKUS_ORDERED", db.OpenRecordset(strSQL), SKUS_ORDERED = curSKU2)
...
Where is the type mismatch?
Can anyone help me out?
EDIT:
...
Set fld_orders = rst_orders.Fields("ORDER")
curOrder = fld_orders.Value
Dim temp As String
temp = DLookup("SKUS_ORDERED", "ORDER_DATA", "SKUS_ORDERED = '" & curSKU2 & "' AND [ORDER] = " & curOrder)
If temp <> Null Then MsgBox temp
...
The entire code is pretty long but here's a larger snippet of where curOrder is initialized, this is inside a nested loop, curSKU2 is initialized earlier outside the loop. Hope it helps.
The mismatch occurs because the second parameter needs to be a string, not a RecordSet.
If any of the parameters in the third argument is a variable (like in your case), the third argument needs to be a concatenated string as well:
temp = DLookup("SKUS_ORDERED", "ORDER_DATA", _
"SKUS_ORDERED = '" & curSKU2 & "' and ORDER = " & curOrder)
EDIT:
Without more code, it's difficult to see where you are using Null.
Are the table name and the column names correct?
What types are your variables? Do they really have values?
Can you post some more code where we can see how you declare and fill the variables?
The "_" character indicates a line break. I could have written the whole statement in one line, but then you'd have to scroll to see it completely:
temp = DLookup("SKUS_ORDERED", "ORDER_DATA", "SKUS_ORDERED = '" & curSKU2 & "' and ORDER = " & curOrder)
EDIT 2:
Could you show the parts where both variables are declared and where curSKU2 is initialized as well? With what you posted, one still can't see if curSKU2 is even filled and what types both are.
Plus, temp is declared as string, so it can never be Null.
This has two consequences:
If temp <> Null doesn't make sense.
DLookup returns Null when no record is found, so the type mismatch could be in the line temp = DLookup(...).
Try temp = Nz(DLookup(...)) instead.
I suggest you change this section of your code ...
Dim temp As String
temp = DLookup("SKUS_ORDERED", "ORDER_DATA", "SKUS_ORDERED = '" & curSKU2 & "' AND [ORDER] = " & curOrder)
to this ...
Dim temp As String
Dim strCriteria As String
strCriteria = "SKUS_ORDERED = '" & curSKU2 & "' AND [ORDER] = " & curOrder
Debug.Print strCriteria
Debug.Print TypeName(DLookup("SKUS_ORDERED", "ORDER_DATA", strCriteria))
temp = DLookup("SKUS_ORDERED", "ORDER_DATA", strCriteria)
If you get an error, switch to the Immediate Window to view the output from the Debug.Print statements.
The first will give you the text for a WHERE condition which you can test in a new query:
SELECT SKUS_ORDERED FROM ORDER_DATA WHERE [strCriteria text here]
The TypeName() function will tell you the data type of the value returned by DLookup(). If TypeName says Null, you will get an error when you try to assign it to a string variable (temp), because a string value can never be Null.