1

Wondering how variables work when used in a Case statement. It seems like they are declared in the first Case, regardless of whether that Case is relevant.

'The following code will throw an error

Select Case team
    Case "Philadelphia Eagles"
        dim record as String
    Case "Dallas Cowboys"
        dim record as String
End Select

Even if 'team' isn't Philadelphia Eagles, it claims I've already declared the variable 'record'

I was under the impression that anything in a case statement was completely skipped over if that case wasn't relevant.

'The following code works

Select Case team
    Case "Philadelphia Eagles"
        dim record as String
    Case "Dallas Cowboys"
        record = "8-8"
End Select

Just want to confirm that I am understanding the Case statement correctly here.

Thank you!

Josh

Community
  • 1
  • 1
jwinigrad
  • 13
  • 3
  • 1
    Variable declaration is considered before the code enters the scope (global or local). You can test it by debugging the code (you will see that the line with the `Dim ...` is skipped. Hence, it doesn't matter if the declaration is inside or outside the `Case` clause, when your code starts running that variable is already taking a little cell in your stack memory. If you want to change the type depending on the case, declare `As Variant`. – Matteo NNZ Mar 26 '15 at 18:32
  • A good explanation of declaring variables can be found here : [Variables and Data Types](http://www.functionx.com/vbaexcel/Lesson03.htm) – kolcinx Mar 26 '15 at 19:18

1 Answers1

2

Variable declarations (Dim statements) are resolved at the start of the execution of the program, which is why your Dim record statements weren't "skipped" over in your example.

You should put your variable declarations once at the top of your code, just after you start the subroutine or function. You cannot use Dim on the same variable twice. If the variable is an array which you need to resize, you can use ReDim [Preserve] instead.

Sub Subname()
    Dim record as String

    Select Case team
        Case "Philadelphia Eagles"
            record = "16-0"
        Case "Dallas Cowboys"
            record = "8-8"
    End Select

End Sub
AdmiralWen
  • 701
  • 6
  • 16
  • Good explanation! The exception to this rule (kind of) is conditional compilation, but that's not in scope of this question :) – David Zemens Mar 26 '15 at 19:12