0

A really basic question I m afraid:

How do I use a value as any part of an array?

Sub test()

Dim x As Variant
x = Array(1, 2, 3, 8, 9, 10, 1585)

    If InStr(Cells(1,1).Value, x) Then
        MsgBox "OK"
    End If

End Sub

In this code I am trying to check if the cell contains any value from the array

1
  • I don't want to complicate the question too much, but it's important to consider some other factors, namely the array size and the number of searches against the array per "session." If you are actually working with a 5 - 10 element array, then it won't make much of a difference. But, if you are loading a large array into memory, and performing a number of searches against it, you can expect performance issues. Commented Aug 17, 2018 at 13:09

2 Answers 2

1

You can use Match and check whether a number is returned (which means the value is found in the array).

Sub test()

Dim x As Variant

x = Array(1, 2, 3, 8, 9, 10, 1585)

If IsNumeric(Application.Match(Cells(1, 1).Value, x, 0)) Then
    MsgBox "OK"
End If

End Sub
Sign up to request clarification or add additional context in comments.

Comments

1

Alternatively, if it doesn't have to be an array one could simply use a string as such:

Sub test()

Dim arrayString As String

  arrayString = "1, 2, 3, 8, 9, 10, 1585"
  If InStr(1, arrayString, Cells(1, 1), vbTextCompare) > 0 Then
    MsgBox "OK"
  End If

End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.