Raf*_*pov 4 excel vba excel-vba
我有If Not2声明,or但代码运行仍然像它是常规If声明.Moncol是一个等于13的整数变量,if语句应该转到End If,而不是.此代码应在Moncol不等于12或13或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
Run Code Online (Sandbox Code Playgroud)
尝试Select Case相反,具有多个场景时If和Else,它更容易使用和阅读.
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
Run Code Online (Sandbox Code Playgroud)
编辑1:关注@Rory注释,你也可以使用Case 12 To 14,这可能会派上用场,特别是对于有很多值的范围,你可以使用Case 12 To 30等等.
您当前的 If 语句将始终为 True。
你可以做:
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
Run Code Online (Sandbox Code Playgroud)