vb.netselect-case

VB Case condition is true but, action is not executed


I've write the following VB code.

Dim qu1, qu2, facroredload, bx, iterations, q3, err As Double
                
bx = 0.1
qu1 = "constant"

For iterations = 0 To 10000
    qu2 = "constant" * bx
    q3 = qu1 + qu2
    facroredload = "constant" / bx ^ 2
    err = Math.Abs(q3 - facroredload)

    Select Case err
        Case > 10
            bx += 0.1
        Case err <= 10 And err > 1
            bx = bx + 0.01
        Case err <= 1 And err > 0.1
            bx = bx + 0.001
        Case err <= 0.1 And err > 0.01
            bx = bx + 0.0001
        Case err < 0.01
            Exit For
    End Select
Next

bx value reaches 1.700000000004 (I don't know why the code adds too many decimals) and then it never changes. The For statement still exciting but, bx never goes beyond 1.7 even though Case err <= 10 And err > 1 is true.


Solution

  • VB's Select Case is really just a fancy if statement. How each Case gets translated to an if expression depends on the format of the case expression. There are three options:

    Once you understand this you should be able to see why your second Case statement doesn't work for you. If err is 1.7, then the second case statement boils down to If err = True, but err is not True, it is a number between 1 and 10.

    To fix your code you have a couple of options. The simplest solution is this:

        Select Case err
            Case > 10
                bx += 0.1
            Case > 1
                bx = bx + 0.01
            Case > 0.1
                bx = bx + 0.001
            Case > 0.01
                bx = bx + 0.0001
            Case Else
                Exit For
        End Select
    

    If more than one Case is satisfied, only the first satisfied clause will be executed, just like an If/ElseIf. That's why the code above works even though it only specifies the lower bound of each range. If you don't like the implied upper bound, you can add it like this: Case > 1 And err <= 10. Personally I think it's actually clearer to leave off the upper bound of each range.