Results 1 to 4 of 4

Thread: [RESOLVED] Working with Array VBA Excel

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2006
    Location
    Montreal, Canada
    Posts
    152

    Resolved [RESOLVED] Working with Array VBA Excel

    Is there a faster way to find the index of a value contained in an array than looping the entire array and compare the value you want to find to the value of the index???

    EX:

    VB Code:
    1. For lnCounter = 0 To UBound(TheArray, 2)
    2.     If MyValue = TheArray(lnCounter,1) then
    3.         MyIndex = lnCounter
    4.     End If
    5. Next lnCounter

    Thanks

  2. #2
    Frenzied Member DKenny's Avatar
    Join Date
    Sep 2005
    Location
    on the good ship oblivion..
    Posts
    1,171

    Re: Working with Array VBA Excel

    No there isn't a better way, but you could optimize your code by including an EXIT FOR statement within your IF...THEN. That way you only loop through the array until you find the value.
    VB Code:
    1. For lnCounter = 0 To UBound(TheArray, 2)
    2.     If MyValue = TheArray(lnCounter, 1) Then
    3.         MyIndex = lnCounter
    4.         Exit For
    5.     End If
    6. Next lnCounter
    Declan

    Don't forget to mark your Thread as resolved.
    Take a moment to rate posts that you think are helpful

  3. #3
    Don't Panic! Ecniv's Avatar
    Join Date
    Nov 2000
    Location
    Amsterdam...
    Posts
    5,343

    Re: Working with Array VBA Excel

    If your array is already sorted you can do the search which moves by halves.

    ie
    1
    2
    3
    4
    5
    6
    7


    You look for 5.
    The program first moves to the half way point (4) says its looking for greater than this.
    It then looks at the next 4, divides in half again, and checks 6
    The program now says its looking for lower, so between positions 4 and 6.
    Then it halves the remaining list items and returns 5.

    There are other methods too.

    BOFH Now, BOFH Past, Information on duplicates

    Feeling like a fly on the inside of a closed window (Thunk!)
    If I post a lot, it is because I am bored at work! ;D Or stuck...
    * Anything I post can be only my opinion. Advice etc is up to you to persue...

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Jan 2006
    Location
    Montreal, Canada
    Posts
    152

    Re: Working with Array VBA Excel

    thanks for the advise

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width