+ Reply to Thread
Results 1 to 2 of 2

"Static" Behavior without Static Defn

  1. #1
    Steve Drenker
    Guest

    "Static" Behavior without Static Defn

    The variable "sEscRate" is behaving as if it is declared Static in the
    following subroutine & function. I'm puzzled why this is. Each invocation of
    the function in the sub should be passing it the variable sEscRate with a
    value of 0.05. I am expecting each time TestFunc will return 1.05, not the
    totalized amount.

    Why is it behaving as if it were declared Static? What am I missing here?

    Sub TestSub()
    Dim sEscRate As Single
    Dim i As Integer

    sEscRate = 0.05
    For i = 1 To 10
    Debug.Print TestFunc(sEscRate)
    Next i
    End Sub


    Function TestFunc(EscRate As Single) As Single
    EscRate = EscRate + 1
    TestFunc = EscRate
    End Function



    Results Results
    Obtained Expected
    1.05 0.05
    2.05 0.05
    3.05 0.05
    4.05 0.05
    5.05 0.05
    6.05 0.05
    7.05 0.05
    8.05 0.05
    9.05 0.05
    10.05 0.05



  2. #2
    Steve Drenker
    Guest

    Re: "Static" Behavior without Static Defn

    D'Oh! I figured it out. It took me a while to remember that parameters
    passed to functions are by default passed "ByRef". A simple "ByVal" in the
    function solves the problem:

    Function TestFunc(ByVal EscRate As Single) As Single

    I swear, if I stop programming in VBA for 4 or 5 months, I must forget half
    of what I struggled to learn in the previous go-round. This little
    brain-fade cost me a couple hours today.

    Steve

    > The variable "sEscRate" is behaving as if it is declared Static in the
    > following subroutine & function. I'm puzzled why this is. Each invocation of
    > the function in the sub should be passing it the variable sEscRate with a
    > value of 0.05. I am expecting each time TestFunc will return 1.05, not the
    > totalized amount.
    >
    > Why is it behaving as if it were declared Static? What am I missing here?
    >
    > Sub TestSub()
    > Dim sEscRate As Single
    > Dim i As Integer
    >
    > sEscRate = 0.05
    > For i = 1 To 10
    > Debug.Print TestFunc(sEscRate)
    > Next i
    > End Sub
    >
    >
    > Function TestFunc(EscRate As Single) As Single
    > EscRate = EscRate + 1
    > TestFunc = EscRate
    > End Function
    >
    >
    >
    > Results Results
    > Obtained Expected
    > 1.05 0.05
    > 2.05 0.05
    > 3.05 0.05
    > 4.05 0.05
    > 5.05 0.05
    > 6.05 0.05
    > 7.05 0.05
    > 8.05 0.05
    > 9.05 0.05
    > 10.05 0.05
    >
    >




+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1