0
Private Sub Worksheet_Change(ByVal Target As Range)

End Sub

On the internet byRef and byVal are differentiated by saying byRef points to a reference and byVal creates a new reference and copies the values from the original. So when you change the passed variable it does not effect the original variable.

But if this is accurate why are the worksheet events such as change and selection_change use byVal. Wouldn't that mean the code should not be able to manipulate the values of the ranges that are being selected. After all byVal should not be able to change the original values only the copies it creates. Yet if you write something like,

Private Sub Worksheet_Change(ByVal Target As Range)
     Target.Font.Color = VBA.ColorConstants.vbBlue
End Sub

Anything written in the selected range will actually change their color. So what is really going on here?

dohaal
  • 11
  • 1

1 Answers1

2
  1. You must know that ByVal still passes references. Even if you get a copy to a referenced object.

  2. Inside of the procedure/event called ByVal you can use the referenced object and change its properties. Such a simple event, works based on what I stated in my first item:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   Target.Interior.Color = vbYellow
End Sub

You practically work with the same object instance (in memory). Only the reference is copied. You can use it inside the sub called ByVal.

  1. The behavior of the variable acts as you tried stating when you use a custom variable and expect to afect somehow (or not) the initial variable value but after calling other Subs handling it.

Please, look to the next example and see how the initial variable is changed in case of the two different processing Subs:

Sub testByValSub()
   Dim x As String
   x = "myString"
   Debug.Print x
   
   changeStrBV x
   Debug.Print "After ByVal: " & x
   
   changeStrBR x
   Debug.Print "After ByRef: " & x
End Sub

Sub changeStrBV(ByVal x)
   x = x & " and something else"
   'do whatever you want with x, but only here...
End Sub
Sub changeStrBR(ByRef x)
   x = x & " and something else"
End Sub
FaneDuru
  • 38,298
  • 4
  • 19
  • 27
  • @dohaal Didn't the above answer clarify your dilema? If something unclear, or not understood from other reason, please do not hesitate to ask for clarifiations. – FaneDuru Jul 18 '21 at 15:00