遍历数组编号值

时间:2018-10-31 18:22:11

标签: arrays vba loops

代码在第一个if语句处中断。工作表范围错误。试图遍历myarray。 myarray是一个整数数组。谢谢!

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim i As Long, myarray As Variant

    myarray = Array(122, 123)

    For i = LBound(myarray) To UBound(myarray)
        If Range("O" & i) <> 0 Then
            answer = MsgBox("Price Change. Are you sure?", vbYesNo)
        End If

        If answer = vbNo Then
            Range("F" & i).Formula = "=IFERROR(VLOOKUP($B" & i & ",eac_equipment_list!$P:$S,2,FALSE),"""")"
        End If

        If answer = vbYes Then
            Range("O" & i) = "0"

        End If
    Next i
End Sub

1 个答案:

答案 0 :(得分:1)

以下是要考虑的几件事:

  1. 请确保SelectionChange仅涉及一个单元格,因为您的代码未设置为处理多个单元格。
  2. 您不需要3个单独的IF语句。这已从3条IF减少到2条(其中一个使用了ElseIf
  3. 如注释中所述,i仅显示数组的索引。如果需要索引的值,则需要使用myarray(i)
  4. 在您的代码顶部添加Option Explicit。您需要声明变量answer

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim i As Long, myarray As Variant, answer As Variant

If Target.Count > 1 Then Exit Sub

myarray = Array(122, 123)

For i = LBound(myarray) To UBound(myarray)
    If Range("O" & myarray(i)) <> 0 Then
        answer = MsgBox("Price Change. Are you sure?", vbYesNo)

        If answer = vbNo Then
            Range("F" & myarray(i)).Formula = "=IFERROR(VLOOKUP($B" & myarray(i) & ",eac_equipment_list!$P:$S,2,FALSE),"""")"
        ElseIf answer = vbYes Then
            Range("O" & myarray(i)) = 0
        End If

    End If
Next i

End Sub