0

I am trying to write a simple function where, based on the parameter I am passing, I need to return a string value. I am getting error Compile error: Syntax error.

Public Function getServer(env As String) As String
    Dim serverName As String
    Select Case env
        Case "DEV"
            serverName = "abc"
            Return serverName;
         Case "TEST"
            serverName = "def"
            Return serverName;
         Case "Prod"
            serverName = "xyz"
            Return serverName;
    End Select
End Function
Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
ktmrocks
  • 361
  • 1
  • 5
  • 18

2 Answers2

5

VBA doesn't use Return to exit a function early, or to specify the returned value of the function. In VBA, you specify early exit using Exit Function; and in order to return a value or object from a function, you have to assign / set the name of the function to the value / object you want to return:

Public Function getServer(env As String) As String
    Select Case env
        Case "DEV"
            getServer = "abc"
        Case "TEST"
            getServer = "def"
        Case "Prod"
            getServer = "xyz"
    End Select
End Function
Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
4

In VBA the Return statement (which does exist) serves an entirely different purpose; it's used in conjunction with the legacy GoSub statement, to return from a subprocedure jump:

    bar = 42
    GoSub Foo
    Exit Sub
Foo:
    Debug.Print bar
    Return

This type of construct is present in the language to support earlier versions/dialects of BASIC, and shouldn't be seen in modern VBA code.

Functions and Property Get procedures return their return value by assigning to the procedure's identifier:

getServer = "abc"

Note that the procedure's identifier is essentially a local variable, and thus the assignment doesn't return. Use Exit Function statements to bail out.

Also, {NEWLINE} is the end-of-instruction marker in VBA, not ; semicolon ;-)

The semicolon is used in VBA to control the behavior of string-printing, e.g. Debug.Print and Write# statements.

Sub test()
    Debug.Print 1; 2; 3;
    Debug.Print 4; 5; 6; ' prints on the same line as the previous statement
End Sub

Whereas this would output on 2 separate lines:

Sub test()
    Debug.Print 1; 2; 3
    Debug.Print 4; 5; 6 ' prints on the next line
End Sub
Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235