0

I am fairly new in vbScript and was wondering if anyone could please advise:

I am trying to loop for a single value in an array. See the following:

Dim reportesTA(3)
reportesTA(0) = "REPORT1"
reportesTA(1) = "REPORT2"
reportesTA(2) = "REPORT3"

I wrote a Sub procedure as follow:

Sub REPORTE1()
    For Each i=0 In reportesTA
        posicionarCursor() ''This is another sub
        commKeys reportesTA(0)
    Next
End Sub

It won't work and I am not sure what I am doing wrong. The other way I though to do this would be:

For i=0 to 0
    posicionarCursor() ''This is another sub
    commKeys reportesTA(0)
Next
2
  • 2
    What do you mean by it won't work? Commented Apr 14, 2015 at 17:42
  • It says that an "In" is expected in the line of "For Each i=0 In reportesTA" Commented Apr 14, 2015 at 17:50

2 Answers 2

2

The size of an array is given by the zero-based last valid index, not the number of elements; so

>> Dim rTA(2) ' 3 elms from 0 to 2
>> rTA(0) = "1"
>> rTA(1) = "2"
>> rTA(2) = "3"

To loop over an array, either use a count/index loop:

>> For i = LBound(rTA) To UBound(rTA)
>>     WScript.Echo i, rTA(i)
>> Next
>>
0 1
1 2
2 3

and access the elements via array(index), or a For Each loop

>> For Each r In rTA
>>     WScript.Echo r
>> Next
1
2
3

giving you access to (a copy of) each element without having to use an index.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to write a sub procedure for each element in the array. So it would be something like "For Each 0 in rTA...do code...Next"? This would be for rta(0)
The For Each sample calls a Sub (WScript.Echo) for each element of rTA.
0

There are two syntax to loop through an array:

For Each i In reportesTA
' your code here
next

or this one:

for i=0 to ubound(reportesTA)
' your code here
next

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.