Search code examples
arraysvbasearchuser-defined-types

VBA – Find object in array with specific property


Let's say I have an object called Card which has several properties like color, number, suit, etc. Then I store a bunch of Cards in an array called deck. Is there a way to search the deck for a Card with a specific property or set of properties?

Thanks!

Theoretical code for Card:

Public color As String
Public suit As String
Public number As Integer

Solution

  • Searching through data is a massive part of programming. There are countless ways to search depending on your needs. To do a basic linear search you could make a loop to the length of the array, and check each array element to see if it meets your criteria.

    Since you haven't tried anything yet, or told us what you want to do with the data you find (or don't find) I'll give you some pseudo code to start you off:

    for(counter integer that increments until it is equal to the length of the array)
    {
        if(array at position[counter] == the color/suit/number your looking for)
        {
            //do whatever
        }
        else
        {
            //do something else
        }
    }
    

    You could make this into a function that takes input, and returns data, so you could call it with whatever data you want to find.

    If this doesn't make sense to you, you will need to start by researching loops.