HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

FizzBuzz in VBA

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
vbafizzbuzzstackoverflow

Problem

FizzBuzz in VBA. Takes start and end numbers as arguments. Will handle any pair of integers to +- 2 Billion or so, determine whether the sequence is increasing or decreasing and output numbers to the immediate window.

Public Sub PrintFizzBuzz(ByVal startNum As Long, ByVal endNum As Long)

    Dim currentNum As Long
    Dim stepValue As Long

    Dim outputString As String
    Dim isFizzBuzz As Boolean

    If startNum <= endNum Then stepValue = 1 Else stepValue = -1

        For currentNum = startNum To endNum Step stepValue

            outputString = ""
            isFizzBuzz = False

            If currentNum Mod 3 = 0 Then
                outputString = outputString & "Fizz"
                isFizzBuzz = True
            End If

            If currentNum Mod 5 = 0 Then
                outputString = outputString & "Buzz"
                isFizzBuzz = True
            End If

            If Not isFizzBuzz Then outputString = CStr(currentNum)

            Debug.Print outputString

        Next currentNum

End Sub

Solution

If startNum <= endNum Then stepValue = 1 Else stepValue = -1

    For currentNum = startNum To endNum Step stepValue


You're evil. Eeeeeee-vil. Properly indented:

If startNum <= endNum Then 
    stepValue = 1 
Else 
    stepValue = -1
End If

For currentNum = startNum To endNum Step stepValue


Indenting that For block under the line that starts with If causes a shortcut in my brain: I skip the rest of the If line and read the For as part of the If block.

Actually, since both alternatives are constant expressions1, you could use IIf here:

stepValue = IIf(startNum <= endNum, 1, -1)
For currentNum = startNum To endNum Step stepValue


outputString = ""


This empty string literal takes up two bytes, when you could have used a null string pointer and used none:

outputString = vbNullString


1 The IIf function evaluates both true and false results, so you don't want side-effects.

Code Snippets

If startNum <= endNum Then stepValue = 1 Else stepValue = -1

    For currentNum = startNum To endNum Step stepValue
If startNum <= endNum Then 
    stepValue = 1 
Else 
    stepValue = -1
End If

For currentNum = startNum To endNum Step stepValue
stepValue = IIf(startNum <= endNum, 1, -1)
For currentNum = startNum To endNum Step stepValue
outputString = ""
outputString = vbNullString

Context

StackExchange Code Review Q#112699, answer score: 9

Revisions (0)

No revisions yet.