View Full Version : Calling a Function from VBA Code


cgdrake
11-05-2008, 05:51 PM
OK, this is driving me nuts. I have a simple function I want to call from a VBA module. Below is the code:

Public Sub CGDTest()
Dim LowPct As Double, LowDeduct As Double

LowPct = 15.9

LowDeduct = CalcLowDeduct(LowPct)

End Sub


Function CalcLowDeduct(LowPct As Double)

LowDeduct = Round((1.349907 * Log(LowPct) + 0.224636 * Log(LowPct) ^ 2 - 0.008581 * Log(LowPct) ^ 3), 2)

End Function


Anyhow, the LowDeduct correctly calculates to 5.27 within the function. However, upon my return to the module, the LowDeduct value changes to 0. What am I doing wrong? Thanks in advance for any help.

WayneRyan
11-05-2008, 06:41 PM
cg,


Public Sub CGDTest()
Dim LowPct As Double, LowDeduct As Double

LowPct = 15.9

LowDeduct = CalcLowDeduct(LowPct) <-- LowDeduct is a LOCAL variable
End Sub


Function CalcLowDeduct(LowPct As Double)

LowDeduct = Round((1.349907 * Log(LowPct) + 0.224636 * Log(LowPct) ^ 2 - 0.008581 * Log(LowPct) ^ 3), 2)

End Function


The function CalcLowDeduct is never assigned a value

hth,
Wayne

pbaldy
11-05-2008, 06:48 PM
To do it the way you are, LowDeduct would have to be a public variable rather than declared within your first function.

CyberLynx
11-05-2008, 08:48 PM
Like This....


Public Sub CGDTest()
Dim LowPct As Double, LowDeduct As Double

LowPct = 15.9

LowDeduct = CalcLowDeduct(LowPct) <-- LowDeduct is a LOCAL variable
'.....................
'.....................
'The rest of your code that will use the LowDeduct variable.
'If this variable will be processed elsewhere in the Database Form
'then you would declare (Dim) the variable within the declarations
'section of the Form or if it goes further than the Form then you
'would declare the variable as Public within a Database Code Module.
'.....................
'.....................
End Sub


Public Function CalcLowDeduct(ByVal dblVal As Double) As Double
CalcLowDeduct = Round((1.349907 * Log(dblVal) + 0.224636 * Log(dblVal) ^ 2 - 0.008581 * Log(dblVal) ^ 3), 2)
End Function


.

cgdrake
11-06-2008, 06:13 AM
Thanks for the help, I will try it that way.