user4838695
user4838695

Reputation:

Why am I getting variable not found errors?

I am getting undeclared variable errors with my code and I don't know why! The variables are declared above, but when being used, they are not found! The error in question occurs on the variables with two stars

    If hour >= 10 Then
        Dim hourAnn = My.Resources.ResourceManager.GetObject("_" + hour.ToString)
    Else
        Dim hourAnn = My.Resources.ResourceManager.GetObject("_0" + hour.ToString)
    End If

    If minute >= 10 Then
        Dim minuteAnn = My.Resources.ResourceManager.GetObject("_" + minute.ToString)
    Else
        Dim minuteAnn = My.Resources.ResourceManager.GetObject("_" + minute.ToString)
    End If

    'Ann Type
    If annType = 1 Then
        My.Computer.Audio.Play(My.Resources.nowApproachPlatform, AudioPlayMode.WaitToComplete)  'The train now approaching platform
        My.Computer.Audio.Play(platformAnn, AudioPlayMode.WaitToComplete)                       'x
        My.Computer.Audio.Play(My.Resources.isThe, AudioPlayMode.WaitToComplete)                'is the
        My.Computer.Audio.Play(**hourAnn**, AudioPlayMode.WaitToComplete)                '<hour>
        My.Computer.Audio.Play(**minuteAnn**, AudioPlayMode.WaitToComplete)                '<min>

Upvotes: 2

Views: 114

Answers (1)

Jordumus
Jordumus

Reputation: 2783

Variables are only known in the scope they are created.

If you create a variable in an if-structure, they are only known inside that if. Same counts for functions, for-loops and any other "containing" structures.

Solution for your code:

Dim hourAnn = ""
 If hour >= 10 Then
        hourAnn = My.Resources.ResourceManager.GetObject("_" + hour.ToString)
    Else
        hourAnn = My.Resources.ResourceManager.GetObject("_0" + hour.ToString)
    End If

Dim minuteAnn = ""
If minute >= 10 Then
    minuteAnn = My.Resources.ResourceManager.GetObject("_" + minute.ToString)
Else
    minuteAnn = My.Resources.ResourceManager.GetObject("_" + minute.ToString)
End If

Want to learn more? Read here

Upvotes: 4

Related Questions