VBA循环多个条件(AND,OR)

时间:2014-07-30 15:43:59

标签: excel vba

我正在尝试检查多个条件,如果它们没问题,请继续。否则应该有消息。运行宏但它不捕获错误(例如,第-2列中没有资金#)并且没有按预期提供错误消息。有什么问题?

Sub CheckFundsInISAccounts()

'Version 9 change.

Dim c As Range
Dim lstRng As Range
Dim LastRow As Integer

Application.ScreenUpdating = False

Worksheets("DataFile").Activate
Range("U2").Activate

LastRow = Cells(Rows.count, "A").End(xlUp).row

Set lstRng = Range("U2", Range("U65536").End(xlUp))


For Each c In lstRng
    If c.Value > 29999 And c.Offset(0, -2).Value = 10 Or 11 Or 12 Or 20 Or 45 Or 60 Or 70 Then
        c.Offset(1, 0).Select

    Else

      MsgBox ("NOT every IS account has a Fund assigned to it. Double-check it")

    End If

Next c


Columns("A:W").Select
Selection.EntireColumn.AutoFit

Application.ScreenUpdating = True

End Sub

2 个答案:

答案 0 :(得分:1)

c.Offset(0, -2).Value = 10 Or 11 Or 12 Or 20 Or 45 Or 60 Or 70 Then不是正确的代码。您需要单独进行每项测试:

c.Offset(0, -2).Value = 10 Or c.Offset(0, -2).Value = 11 Or c.Offset(0, -2).Value = 12 Or c.Offset(0, -2).Value = 20 Or c.Offset(0, -2).Value = 45 Or c.Offset(0, -2).Value = 60 Or c.Offset(0, -2).Value = 70 Then

当然有更方便的方法,例如将有效值放在列表中并检查该列表是否包含c.Offset(0, -2).Value

答案 1 :(得分:0)

根据括号的使用,结果有差异

If c.Value > 29999 _
And c.Offset(0, -2).Value = 10 _
Or c.Offset(0, -2).Value = 11 _
Or c.Offset(0, -2).Value = 12 _
Or c.Offset(0, -2).Value = 20 _
Or c.Offset(0, -2).Value = 45 _
Or c.Offset(0, -2).Value = 60 _
Or c.Offset(0, -2).Value = 70 Then

将会有以下不同的结果(可能是您正在寻找的)

If c.Value > 29999 _
And (c.Offset(0, -2).Value = 10 _
    Or c.Offset(0, -2).Value = 11 _
    Or c.Offset(0, -2).Value = 12 _
    Or c.Offset(0, -2).Value = 20 _
    Or c.Offset(0, -2).Value = 45 _
    Or c.Offset(0, -2).Value = 60 _
    Or c.Offset(0, -2).Value = 70) Then