つらつら Excel VBA

私の備忘録です。

多次元配列の完全一致検索

For Each便利。

Sub テスト()
    
    '適当に8次元配列を用意
    Dim myArray(9, 9, 9, 9, 9, 9, 9, 9) As Variant
    
    '適当なテストデータ
    myArray(1, 1, 8, 7, 5, 8, 8, 8) = "test1"
    myArray(8, 8, 8, 1, 1, 8, 7, 5) = "test"
    myArray(5, 8, 8, 8, 1, 1, 8, 7) = "test"
    
    If ArraySearch(myArray, "test") Then Debug.Print "発見!"
    
End Sub

Function ArraySearch(myArray() As Variant, searchString As String) As Boolean
    
    ArraySearch = False
    
    'Dim cnt As Long: cnt = 0
    Dim ar As Variant
    For Each ar In myArray
        'cnt = cnt + 1
        'If cnt Mod 100000 = 0 Then DoEvents 'ハングアップ対策
        
        If ar = searchString Then ArraySearch = True: Exit For
    Next
    
End Function

以上。