Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA If Not Or Statenent

Tags:

excel

vba

I have If Not statement with 2 or but the code runs still like it is regular If statement. Moncol is an integer variable that equales 13 and the if statement should go to End If, and it is not. This code should delete columns just when Moncol not equals 12 or 13 or 14.

With NewPayWS
    If Not MonCol = 12 Or Not MonCol = 13 Or Not MonCol = 14 Then
        .Range(.Cells(1, lastcol - 1), .Cells(1, MonCol + 1)).EntireColumn.Delete
        .Range(.Cells(1, DataType + 1), .Cells(1, MonCol - 4)).EntireColumn.Delete
    End If
End With
like image 278
Rafael Osipov Avatar asked Dec 10 '22 07:12

Rafael Osipov


1 Answers

Try Select Case instead, when having multiple scenarios of If and Else, it's much easier to use, and read.

Select Case MonCol
    Case 12, 13, 14
        ' do nothing

    Case Else
        .Range(.Cells(1, lastcol - 1), .Cells(1, MonCol + 1)).EntireColumn.Delete
        .Range(.Cells(1, DataType + 1), .Cells(1, MonCol - 4)).EntireColumn.Delete

End Select

Edit 1: Following @Rory comments, you can also use Case 12 To 14, this may come handy especially for ranges with a lot of values, then you can use Case 12 To 30, etc.

like image 161
Shai Rado Avatar answered Dec 25 '22 06:12

Shai Rado