How to offset in 1d array

YasserKhalil
PlatinumLounger
Posts: 4513
Joined: 31 Aug 2016, 09:02

How to offset in 1d array

Post by YasserKhalil »

Hello everyone

I am trying to use offset in the 1d array to get the correct item or element inside the 1d array

Code: Select all

Sub Test()
    Dim a, x
    a = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
    Dim start As Integer
    start = Application.Match(6, a, 0)
    
    
    x = 7
    'How can I get the next item in the array offseting by x
    'start would be here equal to 6, so if we offset by x which is 7
    'we would go to the last item in the array which is 12
    Debug.Print "X = " & a(11)
    
    
    x = 9
    'How can I get the next item in the array offseting by x
    'start would be here equal to 6, so if we offset by x which is 9
    'we would go to the second item in the array which is 2
    Debug.Print "X = " & a(1)

End Sub
I have put two examples as x represents the offset amount and explained how to get the correct element from the array

YasserKhalil
PlatinumLounger
Posts: 4513
Joined: 31 Aug 2016, 09:02

Re: How to offset in 1d array

Post by YasserKhalil »

This is my try but I welcome any other ideas

Code: Select all

    If start + x > UBound(a) + 2 Then
        Debug.Print a((start + x - 2) - UBound(a) - 1)
    Else
        Debug.Print a(start + x - 2)
    End If

User avatar
StuartR
Administrator
Posts: 11555
Joined: 16 Jan 2010, 15:49
Location: London, Europe

Re: How to offset in 1d array

Post by StuartR »

I don't completely understand your requirement, but you want something like
Debug.Print "X = " & a((x + start) Mod UBound(a))

UBound(a) is the length of the array, which is 11
Mod substracts 11 from x+start repeatedly until it is less than the length of the array
StuartR


YasserKhalil
PlatinumLounger
Posts: 4513
Joined: 31 Aug 2016, 09:02

Re: How to offset in 1d array

Post by YasserKhalil »

Thanks a lot. I have given examples of the expected results
If x=7 then print X=12
if x=9 then print X=2
To simple words, increment the given x to the start and count till reaching the needed item
Untitled.png
You do not have the required permissions to view the files attached to this post.

User avatar
StuartR
Administrator
Posts: 11555
Joined: 16 Jan 2010, 15:49
Location: London, Europe

Re: How to offset in 1d array

Post by StuartR »

This gives the result you want

Debug.Print "X = " & a((x + start - 2) Mod (UBound(a) + 1))
StuartR


YasserKhalil
PlatinumLounger
Posts: 4513
Joined: 31 Aug 2016, 09:02

Re: How to offset in 1d array

Post by YasserKhalil »

That's perfect. Thank you very much.
I will try to understand it well

Best Regards