Consulting

Results 1 to 2 of 2

Thread: Why do create a temporary variable and then set the value to a function?

  1. #1
    VBAX Tutor Benzadeus's Avatar
    Joined
    Dec 2008
    Location
    Belo Horizonte, Brazil
    Posts
    271
    Location

    Why do create a temporary variable and then set the value to a function?

    Why use

     
    Function ExcelVersion() As String
        Dim temp As String
    On Error Resume Next
        Select Case CLng(Application.Version)
            Case 9: temp = "Excel 2000"
            Case 10: temp = "Excel 2002"
            Case 11: temp = "Excel 2003"
            Case 12: temp = "Excel 2007"
            Case 14: temp = "Excel 2010"
        End Select
        On Error GoTo 0
        ExcelVersion = temp
    End Function
    instead of

    Function ExcelVersion() As String
        On Error Resume Next
        Select Case CLng(Application.Version)
            Case 9: ExcelVersion = "Excel 2000"
            Case 10: ExcelVersion = "Excel 2002"
            Case 11: ExcelVersion = "Excel 2003"
            Case 12: ExcelVersion = "Excel 2007"
            Case 14: ExcelVersion = "Excel 2010"
        End Select
        On Error GoTo 0
    End Function
    ?

    I've seen VBA programmers using the first topology more than the second... is there a reason?

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Probably just a style thing, some programmers don't like to use a function name as though it were a variable, they were probably raised on languages where you explicitly return a value, where you would have to use something like

    Function ExcelVersion() 
        Dim temp As String 
    On Error Resume Next 
        Select Case CLng(Application.Version) 
        Case 9: temp = "Excel 2000" 
        Case 10: temp = "Excel 2002" 
        Case 11: temp = "Excel 2003" 
        Case 12: temp = "Excel 2007" 
        Case 14: temp = "Excel 2010" 
        End Select 
        On Error Goto 0 
        Return temp 
    End Function
    Personally, I wouldn't do it the second way, although I will admit to using the function name where the value is only returned once.
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •