1

I guess this is a easy one but I can't figure it out.

I have an array with multiple items, as it follows:

slds = Array(3, 15, 27, 39, 51, 87, 74, 89, 11, 45, 57, 24)

I want to do a For loop using just some items the array, defined by the position, for example, the first 4 elements, but I don't know the correct syntax for it. Something like

For slds(0) to slds(3) 'do some...

Any ideas?

3
  • 1
    For i = lBound(slds) to Lbound(slds) + 3 Then use slds(i) to refer to the item. Commented Dec 30, 2015 at 14:41
  • 1
    For i = 0 to 3: msgbox slds(i): next i for example. Commented Dec 30, 2015 at 14:42
  • or just redim the array to your chosen length. Commented Dec 31, 2015 at 7:02

2 Answers 2

2

Assuming a typical zero-based array in VBA:

For i = 0 To 3
    'do stuff
    Debug.Print slds(i)
Next

Here you are indicating you want index 0 to 3, or the first 4 elements.

If you can't be certain of zero-based, you'd use
For i = lBound(slds) to Lbound(slds) + 3as mentioned by Scott Craner

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

Comments

2

Or you could just Redim the array to capture the first x values.

For loop retained in case you still want to loop.

Sub a()
Dim slds
Dim lngCnt As Long
slds = Array(3, 15, 27, 39, 51, 87, 74, 89, 11, 45, 57, 24)
ReDim Preserve slds(1 To 3)
For lngCnt = 1 To UBound(slds)
    Debug.Print slds(lngCnt)
Next
End Sub

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.