我遇到一个小问题,每个循环遍历一个整数数组。我有这样的事情:
Dim arr(3) as Integer
Dim vari as variant
for each vari in arr
debug.print vari
next var
虽然它确实正确地返回了值,但我还需要一种方法来引用数组中给定项的索引号(无论是arr(1),(2)等)。如何为每个循环执行此操作?我知道如何使用for x = y to z
循环来实现它,但我宁愿将其保留为每个循环。
答案 0 :(得分:5)
如果想要轻松访问元素索引,则需要使用传统的for循环。试试这个......
app.use('/admin', function(req,res,next){
if(req.user){
return express.static(path.join(__dirname, 'public'));
} else {
res.render(403, 'login', {message:'Please, login!'});
}
});
没有方法可以从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
的文档,它在VB6 / VBA https://msdn.microsoft.com/en-us/library/windows/desktop/ms221053(v=vs.85).aspx
IEnumVARIANT
答案 1 :(得分:0)
如果你真的坚持使用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
答案 2 :(得分:-1)
首先尝试修改它。
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
End Sub