为数组 VBA 上的每个循环检索索引



我遇到了一个小问题,每个循环遍历一个整数数组。我有这样的东西:

Dim arr(3) as Integer
Dim vari as variant
for each vari in arr
  debug.print vari
next var

虽然它确实正确返回了值,但我还需要一种方法来引用数组中给定项目的索引号(无论是 arr(1)、(2) 等)。如何使用 for 每个循环执行此操作?我知道如何使用for x = y to z循环来做到这一点,但我宁愿将其保留为每个循环。

如果你想轻松访问元素索引,你需要使用传统的 for 循环。 试试这个...

Sub Test2()
    Dim arr(3) As Integer
    Dim vari As Variant
    arr(0) = 5: arr(1) = 4: arr(2) = 3: arr(3) = 2
    Dim lIdx As Long
    For lIdx = LBound(arr) To UBound(arr) '* though you have defined the bounds to be 3 above !!  anyway...
        vari = arr(lIdx)
        Debug.Print vari, lIdx
    Next lIdx
'    For Each vari In arr
'      Debug.Print vari
'    Next Var
End Sub

无法For Each循环中获取索引号。 如果你想要证据,那么这里是接口IEnumVARIANT的文档,在VB6/VBA https://msdn.microsoft.com/en-us/library/windows/desktop/ms221053(v=vs.85)中划线For Each.aspx

如果你真的坚持使用 For Each ,那么你需要使用计数器变量来跟踪索引,即以下代码中idx的变量:

Dim arr(1 to 3) as Integer '<-- 1 to 3 if you want your array index start with 1 instead of zero
Dim vari as variant
Dim idx as long: idx = LBound(arr)
For Each vari In arr
    debug.print "The item at index " & idx & " is: " & vari
    idx = idx + 1
Next vari

在这里,请先尝试修改它。

Sub forEachArray()

Dim element As Variant
Dim animals(0 To 5) As String
'We have created an array that can hold 6 elements
animals(0) = "Dog"
animals(1) = "Cat"
animals(2) = "Bird"
animals(3) = "Buffalo"
animals(4) = "Snake"
animals(5) = "Duck-billed Platypus"
'We fill each element of the array

For Each element In animals
'animals consists of 6 "elements"
    Debug.Print element
    'printing to the immediate window
Next

结束子

最新更新