Function is changing a variable in the calling subroutine

musicgold

Board Regular
Joined
Jan 9, 2008
Messages
197
Hi,

I am noticing an unusual behavior that a called function changes a variable of the calling subroutine.

As shown below, subroutine Change_rows() is calling Clean_formula(). What I am noticing is that when the control comes back to Change_rows() the value in formula1 is the same as that in Tempstr2.

I monitored the variables and it appears that the value in formula1 changes as soon as TempStr2 changes inside the function.

Why is this happening? How can I avoid it?


Code:
Public Sub Change_rows()

...

  formula1 = oLine.Cells(1, 3).formula  

  TempStr = Clean_formula([COLOR="#0000FF"]formula1[/COLOR]) 

...
End Sub


Public Function Clean_formula(TempStr2 As String)
' this function removes the / and * signs in a formula

Dim Signs As Integer

    Signs = 0
      Signs = InStr(1, TempStr2, "/")            ' remove any division or multiplcation terms in the formula
      If (Signs > 0) Then TempStr2 = Left$(TempStr2, Signs - 1)
      
      Signs = 0
      Signs = InStr(1, TempStr2, "*")               ' remove any division or multiplcation terms in the formula
      If (Signs > 0) Then TempStr2 = Left$(TempStr2, Signs - 1)
      
       TempStr2 = Replace(TempStr2, "'", "")
      
      Clean_formula = [COLOR="#FF0000"]TempStr2[/COLOR]

End Function
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
It's changing because you are passing the variable ByRef, so the changes in the function are reflected in the actual variable. A simple fix is to pass it ByVal:

Rich (BB code):
Public Function Clean_formula(ByVal TempStr2 As String)
 
Upvote 0

Forum statistics

Threads
1,223,897
Messages
6,175,269
Members
452,628
Latest member
dd2

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