Generic way to check if a key is in a Collection in Excel VBA
<p>I have different Collections in my code. Some hold Objects (of various kinds), others have types (like Long) within them.</p>

<p>Is there a way to check if a key is contained in the Collection that works for types as well as objects?</p>

<p>So far I have two functions.</p>

<p>First function:</p>

<pre><code>Private Function ContainsObject(objCollection As Object, strName As String) As Boolean
    Dim o As Object
    On Error Resume Next
    Set o = objCollection(strName)
    ContainsObject = (Err.Number = 0)
    Err.Clear
End Function
</code></pre>

<p>Second function:</p>

<pre><code>Private Function ContainsLong(AllItems As Collection, TheKey As String) As Boolean
    Dim TheValue As Long
    On Error Resume Next
    TheValue = AllItems.Item(TheKey)
    ContainsLong = (Err.Number = 0)
    Err.Clear
End Function
</code></pre>

<p>The reason for the two functions is that ContainsObject does not seem to work if I pass a Collection that has Longs pairs (the function always returns False.)</p>

<p>P.S.: The first function is a copy of the third answer from <a href="https://stackoverflow.com/questions/6688131/test-or-check-if-sheet-exists">Test or check if sheet exists</a></p>