Search code examples
vbaexcelstatements

Excel multiple if statements to run multiple macros


I have several objects in my Excel and I am exporting them with my macro1, macro2 and macro3. I use "mainmacro" to run all this process. I also have Checkboxes (Form Controls) to choose what objects should be exported. So if Checkbox 1 is checked I have "TRUE" in cell B1 if it is unchecked then in B1 is "FALSE". Same with Checkbox 2 -> B2, Checkbox 3 -> B3.

If in cell B1 is "TRUE" then main macro runs macro1, if B1 is "FALSE" nothing happens. If B2 is "TRUE" then main macro runs macro2, if B2 is "FALSE" then nothing happens. If B3 is "TRUE" then main macro runs macro3, if B3 is F"FALSE" then nothing happens.

All my macros should run independently. So if I choose B1 and B2 to be (by using Checkboxes) "TRUE" then I need to run macro1 and macro2, but not macro3. Same with all combinations possible. Run "TRUE" values and skip "FALSE". My code is not working properly as it runs two first statements but not the last one. What can be the problem?

Sub mainmacro()
Dim ws As Worksheet: Set ws = Sheets("MAIN")
    'declare and set your worksheet, amend as required
    If ws.Range("B1").Value = True Then
        macro1
    If ws.Range("B2").Value = True Then
        macro2
    If ws.Range("B3").Value = True Then
        macro3
    End If
    End If
    End If
End Sub

Solution

  • Close your IF statements since they are independent of each other:

    If ws.Range("B1").Value = True Then
            macro1
    End If
    
    If ws.Range("B2").Value = True Then
            macro2
    End If
    
    If ws.Range("B3").Value = True Then
            macro3
    End If
    

    Alternatele, since your IF statements are single line expressions, you could ignore the end if statements like this:

    If ws.Range("B1").Value = True Then macro1
    
    If ws.Range("B2").Value = True Then macro2
    
    If ws.Range("B3").Value = True Then macro3