Results 1 to 3 of 3

Finding the position of a value in an array

Threaded View

  1. #1
    Forum Contributor
    Join Date
    02-23-2006
    Location
    Near London, England
    MS-Off Ver
    Office 2003
    Posts
    770

    Question Finding the position of a value in an array

    I am aware that you can use Match to find the position of an entry in an array, and the following code works as expected, returning an index of 4:

    Sub test()
    Dim my_array As Variant
    Dim index As Variant
    
    my_array = Array("pop goes the weasel", "bobs your uncle", "nod your head", "this is a test", "tool bag")
    
    On Error Resume Next
    index = Application.WorksheetFunction.Match("this is a test", my_array, 0)
    On Error GoTo 0
    If index = 0 Then
        MsgBox "Not found"
    Else
        MsgBox "Index: " & index
    End If
    End Sub
    The problem is if I don't know the EXACT text that will appear in the array, but only part of it. I am wanting to do something like the VBA .find lookat:=xlpart operation, but on an array rather than a worksheet.
    The following code will return with the "Not Found" message.

    Sub test()
    Dim my_array As Variant
    Dim index As Variant
    
    my_array = Array("pop goes the weasel", "bobs your uncle", "nod your head", "this is a test", "tool bag")
    
    On Error Resume Next
    index = Application.WorksheetFunction.Match("test", my_array, 0)
    On Error GoTo 0
    If index = 0 Then
        MsgBox "Not found"
    Else
        MsgBox "Index: " & index
    End If
    End Sub
    Other than looping through the entire array and doing a Like test on each entry, is there a more elegant (ie. faster) way of searching an array when you only have part of the string?

    Thanks
    Last edited by Phil_V; 06-04-2009 at 06:07 AM.
    If you find the response helpful please click the scales in the blue bar above and rate it
    If you don't like the response, don't bother with the scales, they are not for you

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1