Difference between ByVal and ByRef?

后端 未结 9 2262
囚心锁ツ
囚心锁ツ 2020-12-15 19:34

What is the difference? I always use ByVal, but, I don\'t really have a good idea of when should I and when not...

相关标签:
9条回答
  • 2020-12-15 20:10

    If you pass in a reference, when you modify the value in the method, the variable in the call site will also be modified.

    If you pass value, it's the same as if another variable is created at the method, so even if you modify it, the original variable (at the call site) won't have its value changed.

    So, indeed, you should usually pass variables as value. Only pass as reference if you have an explicit need to do so.

    0 讨论(0)
  • 2020-12-15 20:10

    ByRef, one value will have 2 addresses

    So if x=80 (80 is value and x is address, then for example variable y can be 80 as well, and thus 80 can be accessed by x and y)

    0 讨论(0)
  • 2020-12-15 20:12

    I hope this answers your question

    Sub last_column_process()
    Dim last_column As Integer
    
    last_column = 234
    MsgBox last_column
    
    trying_byref x:=last_column
    MsgBox last_column
    
    trying_byval v:=last_column
    MsgBox last_column
    
    End Sub
    
    Sub trying_byref(ByRef x)
    x = 345
    End Sub
    
    Sub trying_byval(ByRef v)
    v = 555
    End Sub
    
    0 讨论(0)
提交回复
热议问题