Okay, this requires 2 steps:
- a way to substitute the actual field values for the field names, and
- a way to evaluate the resultant expression.
The example below illustrates how you could use the Format event of the
report section where you want the result calculated. It makes several
assumptions:
- For each name in the expression, there is a control on the report with
that name. (This is important due to the way the report optimizer sometimes
doesn't bother to fetch fields if it doesn't see a control on the report
bound directly to the field.)
- Every field name is enclosed in square brackets, and none are of the form:
[Table1].[Field2]
If necessary, alias the field in a query to meet this requirement, or adapt
the code to suit.
- The report has an unbound text box to display the result, and set its
Format property so Access knows its intended data type.
- All the expressions are valid. (Error handling not shown.)
In this example, the field containg the calculation is named Calc, and the
unbound text box for displaying the result is named Text6. The
CalcExpression() function can go in a standard module, so you can call it
from different reports.
Private Sub Detail_Format(Cancel As Integer, FormatCount As Integer)
Me.Text6 = CalcExpression(Me, Me.Calc.Value)
End Sub
Public Function CalcExpression(rpt As Report, varExpression As Variant) As
Variant
Dim varArray As Variant
Dim i As Long
Dim lngPos As Long
Dim lngLen As Long
Dim strName As String
Dim strOut As String
If Len(varExpression) > 0 Then
varArray = Split(varExpression, "[")
If IsArray(varArray) Then
For i = LBound(varArray) To UBound(varArray)
lngPos = InStr(varArray(i), "]")
If lngPos > 0 Then
strName = "[" & Left(varArray(i), lngPos)
strOut = strOut & rpt.Controls(strName)
End If
lngLen = Len(varArray(i))
If lngPos < lngLen Then
strOut = strOut & Mid(varArray(i), lngPos + 1)
End If
Next
End If
Debug.Print strOut, Eval(strOut)
End If
If strOut <> vbNullString Then
CalcExpression = Eval(strOut)
Else
CalcExpression = Null
End If
End Function
--
Allen Browne - Microsoft MVP. Perth, Western Australia
Reply to group, rather than allenbrowne at mvps dot org.
message
news:
[email protected]...