Nefariis
Nefariis

Reputation: 3549

Calling a Sub and returning a value

I'd like to think that I am decent at Visual Basic, but, while I was learning JavaScript the other day, I found something that seemed awesome and now I can't figure out how to do it in Visual Basic.

In JavaScript, it looks like this:

var someValue = getThatValue()

It's both calling and setting the value from the getThatValue() sub. What is the Visual Basic equivalent?


I've tried doing this:

   Private Sub main()
       Dim value = getValue()
       ' Do something with value
   End Sub

   Private Sub getValue()
       return 3
   End Sub

That doesn't seem to work. How can I get that to work?

Upvotes: 27

Views: 139650

Answers (3)

jimifiki
jimifiki

Reputation: 5544

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

Upvotes: 1

George Filippakos
George Filippakos

Reputation: 16569

You should be using a Property:

Private _myValue As String
Public Property MyValue As String
    Get
        Return _myValue
    End Get
    Set(value As String)
        _myValue = value
     End Set
End Property

Then use it like so:

MyValue = "Hello"
Console.write(MyValue)

Upvotes: 0

Kevin
Kevin

Reputation: 2688

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

Upvotes: 41

Related Questions