Saltar al contenido

VBA If declaraciones con múltiples condiciones

    Introducción

    Una de las cosas más comunes en la codificación es construir una lógica que verifique la ocurrencia de múltiples condiciones. Con suerte, estará de acuerdo en que esta es una de las tareas de codificación más comunes, ya sea principiante o experimentado.

    En VBA, las declaraciones If se usan a menudo para construir dicha lógica. Por ejemplo, puede crear una lógica que verifique si el clima es bueno hoy.

    Si es así, puedes salir de casa. Si no, comprueba si está lloviendo un poco o si es una ventisca. Si llueve un poco y tienes tu chubasquero listo, puedes irte. Este es un escenario simple, pero se parece a problemas de codificación comunes.

    Por lo general, podemos manejar dicha lógica utilizando la declaración IF con múltiples condiciones. Una alternativa que tiene sentido bajo ciertas condiciones es usar la instrucción Select Case. En esta guía nos centraremos en la If Declaración con múltiples condicionespero también cubriremos brevemente los conceptos básicos de la declaración Select Case, así como cuándo usarla.

    Diagrama de flujo con si o lógica sobre si salir o no a la calle

    Sentencia IF de tabla de sintaxis

    DescripciónFormatoEjemplo
    si entoncesSi [condition is true] Después [do something] Terminara siIf Good_Weather = True Then MsgBox “Go Out” End If
    Si sin Fin Si (solo una linea)Si [condition is true] Después [do something]If Good_Weather then MsgBox “Go Out”
    Si otroSi [condition is true] Después [do something] De lo contrario [do something] Terminara siIf Rain_Coat_Ready = True Then MsgBox “Go Out” Else MsgBox “Stay Home” End If
    si elseifSi [condition 1 is true] Después [do something] OtroSi [condition2 is true] Después [do something] Terminara siIf Good_Weather = True Then Msgbox “Go Out” ElseIf Good_Weather = False AND Rain_Coat_Ready = True Then Msgbox “Go Out” End if
    ElseIf y Else (debe estar en este orden)Si [condition1 is true] Después [do something] OtroSi [condition 2 is true] Después [do something] Terminara siIf Good_Weather = True Then Msgbox “Go Out” ElseIf Good_Weather = False AND Rain_Coat_Ready = True Then Msgbox “Go Out” Else Msgbox “Stay Home” End if

    Puertas lógicas

    XYY RESULTADOO RESULTADO
    DONDEDONDEYDONDE
    DONDEFALSOFALSODONDE
    FALSODONDEFALSODONDE
    FALSOFALSOFALSOFALSO

    Ejemplo 1: ¿Debería salir hoy?

    Desarrollaremos la lógica del diagrama anterior paso a paso.

    Sub ShouldIGoOutToday()
    'Set the weather to good or bad
    Good_Weather = False
    'Set the Rain coat to ready or not
    Rain_Coat_Ready = True
    'Set the type of bad weather
    Bad_Weather = "Some Rain"
    If Good_Weather = True Then
        'if weather is good then go out
        MsgBox "Go Out"
    Else
        'if weather is not good
        If Bad_Weather = "Some Rain" Then
        'If the bad weather is some rain
            If Rain_Coat_Ready = True Then
            'If the bad weather is some rain and the rain coat is ready
                MsgBox "Go Out"
            Else
                'if the bad weather is some reain and the rain coat is not ready
                MsgBox "Stay Home"
            End If
        ElseIf Bad_Weather = "Blizzard" Then
        'if the bad weather is blizzard
            MsgBox " Stay Home"
        End If
    End If
    End Sub
    
    Ejemplo 1 código vba

    Ejemplo 2: Usando AND/OR

    Puede especificar varias condiciones dentro de la misma condición utilizando AND y OR. En lugar de comprobar que condition = Truepodemos comprobar eso condition1 = True AND condition2 = True. Esto se puede aplicar al ejemplo anterior al ver si el mal tiempo es ‘algo de lluvia’ Y el impermeable está listo.

    Sub ShouldIGoOutTodayEx2()
    'Set the weather to good or bad
    Good_Weather = False
    'Set the Rain coat to ready or not
    Rain_Coat_Ready = True
    'Set the type of bad weather
    Bad_Weather = "Some Rain"
    If Good_Weather = True Then
        'if weather is good then go out
        MsgBox "Go Out"
    Else
        'if weather is not good
        If Bad_Weather = "Some Rain" And Rain_Coat_Ready = True Then
        'If the bad weather is some rain AND the rain coat is ready then Go Out
                MsgBox "Go Out"
        ElseIf Bad_Weather = "Blizzard" Or Rain_Coat_Ready = False Then
        'if the bad weather is blizzard or the rain coat is not ready then Stay Home
            MsgBox " Stay Home"
        End If
    End If
    End Sub
    
    código de ejemplo 2

    Para obtener más información sobre el uso de AND y OR con instrucciones If, consulte este artículo:

    https://software-solutions-online.com/vba-si-o/

    Alternativa a la instrucción If: Select Case

    La forma más obvia de seleccionar el caso es hacer algo cuando solo estamos interesados ​​en el valor de una determinada variable y las cosas que hagamos dependerán del valor de esa variable.

    En nuestro ejemplo anterior, no hay una sola variable de la que dependamos para determinar el resultado. Intentaremos implementar la lógica anterior usando Seleccione el caso.

    La principal diferencia entre el Seleccione el caso y Si declaraciones es que Seleccione el caso le permite ‘hacer algo’ solo en función del valor de la Seleccione el caso variable. Para superar este obstáculo, puede establecer la variable Seleccionar caso en Verdadero. Luego especifica la condición completa detrás de la palabra clave Caso y lo que queremos hacer si se pasa en la siguiente línea.

    Por lo tanto, en lugar de esta sintaxis:

    If X = 2 and Y = 3 then

    [do something]

    End if

    Con Select Case es esta sintaxis:

    Select Case True

    Case X = 2 and Y = 3

    [do something]

    End Select

    La implementación completa de los ejemplos anteriores usando Select Case se muestra a continuación:

    Sub ShouldIGoOutTodayEx3()
    'Set the weather to good or bad
    Good_Weather = False
    'Set the Rain coat to ready or not
    Rain_Coat_Ready = False
    'Set the type of bad weather
    Bad_Weather = "Some Rain"
    
    Select Case True
    
        Case Good_Weather = True
        MsgBox "Go Out"
        
        Case Good_Weather = False And Bad_Weather = "Some Rain" And Rain_Coat_Ready = True
        MsgBox "Go Out"
        
        Case Good_Weather = False And Bad_Weather = "Some Rain" And Rain_Coat_Ready = False
        MsgBox "Stay Home"
    
        Case Good_Weather = False And Bad_Weather = "Blizzard"
        MsgBox "Stay Home"
     
    End Select
    End Sub 
    
    Seleccionar código de ejemplo de caso

    Descripción general

    Las declaraciones If son ideales para manejar lógica simple y compleja que involucra múltiples condiciones y cosas que queremos que sucedan en consecuencia. Por otro lado, Select Case también se puede usar como una alternativa, pero generalmente está destinado a una situación en la que queremos seleccionar una cosa para hacer entre varias cosas posibles. A medida que la lógica se vuelve más compleja y se agregan más niveles a la lógica, Select Case se vuelve menos intuitivo.

    Consulte también: Resolver el error «Finalizar si sin bloquear si»: ¡no encuentre este error!

    Su Calificación Nos Ayuda a Mejorar