PDA

View Full Version : Calling Subroutines in VB



suboro
07-04-2018, 04:03 AM
hi guys, I am pretty new to VB. I am calling 2 subroutines and passing one of the parameters x as Integer.Before calling the subroutines lets say the value of x was 10 and then its incremented by 1 and post that it should call the subroutines with the value x+1 but every time its calling the subroutines its calling with x (ex. 10) not x+1 (ex. 11).What can be the possible cause? I have checked variable type mismatch.Please help.

Paul_Hossler
07-04-2018, 07:24 AM
Without seeing any code (<-- Hint) I'm guessing that it's possibly related to the ByRef or ByVal calling convention

To change the parameter value outside the scope of the called sub, you should use ByRef

ByRef passes the address of the variable to change, and ByVal makes a copy of the variable and only lets the sub work on a copy of the original

Example:




Option Explicit

'ByVal Optional. Indicates that the argument is passed by value.
'ByRef Indicates that the argument is passed by reference. ByRef is the default in Visual Basic.

Sub One()
Dim N As Long
N = 10
'passed ByVal so Sub does NOT change the value outside of the called sub
TwoA N
TwoA N
TwoA N
N = 10
'passed ByRef so Sub does change the value outside of the called sub
TwoB N
TwoB N
TwoB N

End Sub


Sub TwoA(ByVal x As Long)
MsgBox "TwoA - Input = " & x
x = x + 1
MsgBox "TwoA - Added = " & x
End Sub

Sub TwoB(ByRef x As Long)
MsgBox "TwoB - Input = " & x
x = x + 1
MsgBox "TwoB - Added = " & x
End Sub