PDA

View Full Version : Is there a way to write this "for" loop?



alex009988
07-30-2019, 10:09 AM
I need to rewrite c++ program to vba.
I've made a function and the sub, but I dont know how to write this for loop correctly in vba


for (pos=pos-1; a[pos] == 0; pos--)
{
}

Unfortunately this dosent work as this is not a good option to write after "To" something like a(pos) = 0.

For pos = pos - 1 To a(pos) = 0 Step -1
Next pos
I've got extra consultation in this thread http://www.cplusplus.com/forum/beginner/258650/
So I need to create for loop that search first a(pos) = 0 from right to left in the array.
It start from pos=pos-1 and ends by when a(pos) = 0. Any idea how to write this loop for vba?
Regards,
Alex

Bob Phillips
07-30-2019, 10:54 AM
My guess


pos = pos-1
Do While a(pos) <> 0

pos = pos -1
Loop

Paul_Hossler
07-30-2019, 10:57 AM
C++ is one of the many things I don't know

I also didn't understand the "right to left in the array" comment. Arrays have a lower bound(s) and upper bound(s)

Here's some VBA loop-ology examples that you might be able to use




Option Explicit

Sub cPlusPlus()
Dim i As Long
Dim pos As Variant

pos = Array(1, 2, 3, 4, 5, 0, 6, 7, 8, 9)


'case 1
For i = LBound(pos) To UBound(pos)
Debug.Print "Case 1", i, pos(i)
Next


'case 2
For i = LBound(pos) To UBound(pos)
If pos(i) = 0 Then Exit For
Debug.Print "Case 2", i, pos(i)
Next


'case 3
i = LBound(pos)
Do While pos(i) <> 0 And i <= UBound(pos)
Debug.Print "Case 3", i, pos(i)
i = i + 1
Loop

'case 4
i = LBound(pos)
Do
Debug.Print "Case 4", i, pos(i)
i = i + 1
Loop Until pos(i + 1) = 0 Or i = UBound(pos)


End Sub