VBA if not or

I have an operator If Notwith 2 or, but the code still works as a regular operator If. Moncol is an integer variable that is 13, and the if statement should go to End If, which is not the case. This code should remove columns only when Moncolnot equal to 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
+4
source share
3 answers

Try Select Caseinstead, with several scenarios Ifand Elseit is 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

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

+6
source

Your current If statement will always be True.

You can do:

With NewPayWS
    If Not (MonCol = 12 Or MonCol = 13 Or 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
+4
source

There are several processing methods. Here is another one

If moncol >= 12 and moncol <=14 then
     'Do nothing
else
     'delete code
end if
+2
source

Source: https://habr.com/ru/post/1695050/


All Articles