VBA Code Library
Check if a value is in an array with this VBA function. If the value is in the VBA array, the function returns true. If the value is not in the array or the array is empty, the VBA function returns false.
The function accepts two variants, so it can look for a string in a string array, an integer in an integer array, or whatever you’d like as long as you pass it converted data types. The first argument is the value you want to find and the second argument is the array you want to search.
I’ve included a demo at the bottom showing how you can convert a number to a string while using the
Check if Value is in Array using VBA
Private Function IsInArray(valToBeFound As Variant, arr As Variant) As Boolean 'DEVELOPER: Ryan Wells (wellsr.com) 'DESCRIPTION: Function to check if a value is in an array of values 'INPUT: Pass the function a value to search for and an array of values of any data type. 'OUTPUT: True if is in array, false otherwise Dim element As Variant On Error GoTo IsInArrayError: 'array is empty For Each element In arr If element = valToBeFound Then IsInArray = True Exit Function End If Next element Exit Function IsInArrayError: On Error GoTo 0 IsInArray = False End Function
Checking if a value is in an array is an essential skill, but it just scratches the surface of what you can do with VBA arrays. To become really good at using arrays, you’ll need to grab a copy of our comprehensive VBA Arrays Cheat Sheet with over 20 pre-built macros and dozens of tips designed to make it easy for you to handle arrays.
Becoming a VBA expert isn't hard
Over 5000 members are improving their VBA skills for free with our email tutorials. Why don't you join them? Our experts share time-saving VBA tips and we'll give you access to our huge macro library - it's sure to speed up your macro development.
How to use the IsInArray VBA Function
Sub Demo() Dim arr(2) As String Dim i As Integer arr(0) = "100" arr(1) = "50" arr(2) = "2" i = 2 MsgBox IsInArray(CStr(i), arr) End Sub
Before I go, I’m going to take a few seconds to wish all my readers in the States a very Happy Independence Day! I hope you found this 4th of July VBA Code Library example to be a real treat.
Submit a comment below if you like this macro or have more questions. As always, subscribe to my email list, share this article on social media and follow me on Twitter and check out our VBA Q&A community for more great VBA content.