消息框在IF语句中不起作用

时间:2014-07-12 02:38:19

标签: vba

我正在尝试编写一些循环遍历列的代码,并在单元格包含" buy"以外的任何值时发出警告。或者" sel"。它应该在OK上退出sub并继续取消,但是它没有找到买入和卖出值,因为我的所有测试单元都有"买"或"出售"并且仍会出现消息框。请指教。

Set TransSheet = Application.ActiveSheet
LastCell = TransSheet.Cells(Rows.Count, "A").End(xlUp).Row

Dim MsgBoxTrans As Long
For a = LastCell To 2
    v = Cells(a, 10).Value
    If v <> "buy" Or v <> "sel" Then
        MsgBoxTrans = MsgBox("Transaction exists other than BUY or SEL, please filter and check", vbOKCancel, "Warning - Press Cancel to Skip")
        If MsgBoxTrans = vbOK Then
            Exit Sub
        End If
    Else
        End If
    a = a - 1
Next a

1 个答案:

答案 0 :(得分:0)

Doug解释了代码中的逻辑问题。在这里,我们可以在这里做一些额外的改进:

Set TransSheet = Application.ActiveSheet
LastCell = TransSheet.Cells(Rows.Count, "A").End(xlUp).Row
'This variable not really needed:
'Dim MsgBoxTrans As Long

'## Declare your variable "v" as Variant
Dim v as Variant

'## Force "Step -1" rather than using the clunky "a = a-1":

For a = LastCell To 2 Step -1
    v = Cells(a, 10).Value
    If v <> "buy" AND v <> "sel" Then
        '## Evaluate the MsgBox object, assign the button type to "vbOkCancel" so that
        '   it will either be OK (exit sub) or Cancel, which will continue uninterupted
        If MsgBox("Transaction exists other than BUY or SEL, please filter and check", _
                  "Warning - Press Cancel to Skip", vbOkCancel) = vbOK Then Exit Sub
    'Get rid of this "Else" because you're not using it:
    'Else  
    End If
Next a