Hi, I have written this VBA module for a school project in Access 2007, and it works fine in the Immediate Window in the Visual Basic Editor. However when I use it in a query (SQL) the value just doesn't show up. I have no idea why. Here is the module code:
Option Compare Database
Function LoopIngredients(itemName As String) As Long
Dim strSQL As String
Dim rst As Recordset
Dim field As field
Dim temp As Boolean
strSQL = "Select Table2.[Ingredient], Table2.[Price] From Table2"
'open the results read-only
Set rst = CurrentDb.OpenRecordset(strSQL, dbOpenForwardOnly)
If rst.RecordCount > 0 Then
'rst.MoveFirst
Do While Not rst.EOF
For Each field In rst.Fields
If field.Name = "Ingredient" Then
temp = False
If InStr(itemName, field.Value) Then
temp = True
Debug.Print ("Name " & field.Value)
End If
End If
If field.Name = "Price" Then
If temp Then
LoopIngredients = LoopIngredients + field.Value
Debug.Print ("Price " & LoopIngredients)
End If
End If
Next field
rst.MoveNext
Loop
End If
End Function
And here is the output in the immediate window:
?LoopIngredients("Cheese and Tomato Sandwich")
Name Cheese
Price 1
Name Tomato
Price 3
3
Here is the SQL query:
SELECT Table1.ID, Table1.[Item Name], LoopIngredients([Item Name]) AS Price, Table2.ID, Table2.Ingredient, Table2.Price
FROM Table1, Table2;
Any help would be appreciated.