Results 1 to 4 of 4

Thread: Parameter changing once function run

  1. #1
    Board Regular
    Join Date
    Dec 2018
    Posts
    73
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default Parameter changing once function run

    Hey guys, i am making a small function to add up all the numbers between 2 numbers.

    My code:

    Code:
    Sub Sums()    Dim a As Long, b As Long, i As Long, n As Long, ta As Long, tb As Long, ak As Long, bk As Long
        a = 0
        b = -2
        ak = 1
        bk = 1
        If a - b = 0 Or a + b = 0 Then
            n = 0
        Else:
            If a = b Then
                n = a
            Else:
                If a < 0 Then ak = -1
                If b < 0 Then bk = -1
                ta = Tria(a, ak)
                tb = Tria(b, bk)
            End If
        End If
        If a > b Then
            n = ta - tb
        Else:
            n = tb - ta
        End If
        Debug.Print n
    End Sub
    
    
    Function Tria(n As Long, k)
        n = (n * (n + k)) / 2
        Tria = n
    End Function
    Whenever i call the function: tb = Tria(b, bk), my variable b gets changed in the process. Why is this happening?

    Of course if i just do: Tria = (n * (n + k)) / 2 it all works, but i was under the impression that if my variable was dimmed in a separate sub and it should not be reachable? Or do functions work different?
    Last edited by Lavina; Sep 16th, 2019 at 05:22 AM.

  2. #2
    Board Regular
    Join Date
    Mar 2014
    Posts
    2,427
    Post Thanks / Like
    Mentioned
    11 Post(s)
    Tagged
    1 Thread(s)

    Default Re: Parameter changing once function run

    Change the function declaration to Function Tria(ByVal n As Long, k). By default, VBA passes parameters "by reference" (ByRef).

  3. #3
    Board Regular
    Join Date
    Mar 2015
    Location
    Syria
    Posts
    237
    Post Thanks / Like
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)

    Default Re: Parameter changing once function run

    Hi
    try
    Code:
    Function Tria(nn As Long, kk)
        nn = (nn * (nn + kk)) / 2
        Tria = nn
    End Function

  4. #4
    Board Regular
    Join Date
    Dec 2018
    Posts
    73
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default Re: Parameter changing once function run

    Quote Originally Posted by joeu2004 View Post
    Change the function declaration to Function Tria(ByVal n As Long, k). By default, VBA passes parameters "by reference" (ByRef).

    Ah, i see now, thank you!

Some videos you may like

User Tag List

Tags for this Thread

Like this thread? Share it with others

Like this thread? Share it with others

Posting Permissions

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