Parameter changing once function run

Lavina

Board Regular
Joined
Dec 18, 2018
Messages
75
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:

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple
Change the function declaration to Function Tria(ByVal n As Long, k). By default, VBA passes parameters "by reference" (ByRef).
 
Upvote 0
Hi
try
Code:
Function Tria(nn As Long, kk)
    nn = (nn * (nn + kk)) / 2
    Tria = nn
End Function
 
Upvote 0

Forum statistics

Threads
1,223,957
Messages
6,175,622
Members
452,661
Latest member
Nonhle

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top