Skip to main content
edited title
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Using non-explicit return values to simplify code Adding or replacing a sheet in an Excel file

edited tags
Link
Mathieu Guindon
  • 75.1k
  • 18
  • 191
  • 463
Source Link
teepee
  • 203
  • 1
  • 5

Using non-explicit return values to simplify code

I have the following function and want to simplify the code to make it more readable by eliminating redundant lines:

Function AddSheet(shtName As String, Optional readOnlyFlag As Boolean = True) As Boolean  'Add new worksheet to current workbook at the end

    If readOnlyFlag And IsSheet(shtName) Then
        AddSheet = False
        Exit Function
    ElseIf Not readOnlyFlag Then
        If IsSheet(shtName) Then DeleteSheet (shtName)
        With ThisWorkbook:
            .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = shtName
        End With
        AddSheet = True
    End If
    
End Function

Since the first condition (If readOnlyFlag And IsSheet(shtName)) will only assign a return value of False to the function (which should already be the default, as I understand) and then exits the function, would it be acceptable to leave out that aspect of the logic and just have the following:

    If Not readOnlyFlag Then
        If IsSheet(shtName) Then DeleteSheet (shtName)
        With ThisWorkbook:
            .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = shtName
        End With
        AddSheet = True
    End If

In other words, is it best practice to be explicit like the first code block, by stating that the function returns False if that occurs, or to avoid what might be considered redundancy, by using the simplified second version?