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

Round to nearest half hour?
Use =MROUND(A2,"0:30") to round to nearest half hour. Use =CEILING(A2,"0:30") to round to next half hour.
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,224,823
Messages
6,181,177
Members
453,021
Latest member
Justyna P

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