Vba excel проверка значения массива

While this is essentially just @Brad’s answer again, I thought it might be worth including a slightly modified function which will return the index of the item you’re searching for if it exists in the array. If the item is not in the array, it returns -1 instead.

The output of this can be checked just like the «in string» function, If InStr(...) > 0 Then, so I made a little test function below it as an example.

Option Explicit

Public Function IsInArrayIndex(stringToFind As String, arr As Variant) As Long

    IsInArrayIndex = -1

    Dim i As Long
    For i = LBound(arr, 1) To UBound(arr, 1)
        If arr(i) = stringToFind Then
            IsInArrayIndex = i
            Exit Function
        End If
    Next i

End Function

Sub test()

    Dim fruitArray As Variant
    fruitArray = Array("orange", "apple", "banana", "berry")

    Dim result As Long
    result = IsInArrayIndex("apple", fruitArray)

    If result >= 0 Then
        Debug.Print chr(34) & fruitArray(result) & chr(34) & " exists in array at index " & result
    Else
        Debug.Print "does not exist in array"
    End If

End Sub

Then I went a little overboard and fleshed out one for two dimensional arrays because when you generate an array based on a range it’s generally in this form.

It returns a single dimension variant array with just two values, the two indices of the array used as an input (assuming the value is found). If the value is not found, it returns an array of (-1, -1).

Option Explicit

Public Function IsInArray2DIndex(stringToFind As String, arr As Variant) As Variant

    IsInArray2DIndex= Array(-1, -1)

    Dim i As Long
    Dim j As Long

    For i = LBound(arr, 1) To UBound(arr, 1)
        For j = LBound(arr, 2) To UBound(arr, 2)
            If arr(i, j) = stringToFind Then
                IsInArray2DIndex= Array(i, j)
                Exit Function
            End If
        Next j
    Next i

End Function

Here’s a picture of the data that I set up for the test, followed by the test:

test 2

Sub test2()

    Dim fruitArray2D As Variant
    fruitArray2D = sheets("Sheet1").Range("A1:B2").value

    Dim result As Variant
    result = IsInArray2DIndex("apple", fruitArray2D)

    If result(0) >= 0 And result(1) >= 0 Then
        Debug.Print chr(34) & fruitArray2D(result(0), result(1)) & chr(34) & " exists in array at row: " & result(0) & ", col: " & result(1)
    Else
        Debug.Print "does not exist in array"
    End If

End Sub

 

Добрый день.  
Как правильно записать строчку кода, чтобы проверить, является ли массив MyArray непустым? Т.е. если в массиве есть хоть один элемент, то погнали дальше, если нет ни одного, то перескочили.  
Спасибо.

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Sub Arr_Initialize()  
Dim avArr()  
   If (Not Not avArr) = 0 Then  
       MsgBox «массив пуст и записей в нем не было»  
   Else  
       MsgBox «массив заполнен чем-то»  
   End If  
ReDim avArr(1): avArr(1) = 1  
   If (Not Not avArr) = 0 Then  
       MsgBox «массив пуст и записей в нем не было»  
   Else  
       MsgBox «массив заполнен чем-то»  
   End If  
End Sub

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Спасибо большое. Все очень понятно объяснили.  
Правда, не понял смысл двойного отрицания (Not Not).  
Если не затруднит, просветите.

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Впишите в ячейку А1 формулу:  
=НЕ(НЕ(A1=0))  

  Вычислите её пошагово и все поймете.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

{quote}{login=The_Prist}{date=06.06.2010 11:30}{thema=}{post}Впишите в ячейку А1 формулу:  
=НЕ(НЕ(A1=0))  

  Вычислите её пошагово и все поймете.{/post}{/quote}  

  Вписал в ячейку B1 формулу =НЕ(НЕ(A1=0)),  
в ячейку B2 формулу =A2=0.  
Поигрался с нулями,цифрами и пустотами — разницы в работе обеих формул не увидел.

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Эх…Простой конструкцией типа avArr = 0 не получиться узнать наполнение массива — такая конструкция недопустима, сначала необходимо переопределить размерность, т.к. VBA считает, что Вы хотите присвоить массиву значение.  

  В этом выражении:  
Not Not avArr  

  VBA сначала сравнивает массив, преобразуя его в тип Integer, независимо от данных в нем(на сами данные не влияет), не вызывая ошибку.    
В общем-то можно и так записать для достижения цели:  
(Not avArr) = 0    

  Но все равно придется добавлять Not, чтобы было вроде как понятней(или поменять условия местами).  
Не знаю, понятно объяснил или нет — по-другому не умею.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Еще раз спасибо огромное.

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

{quote}{login=The_Prist}{date=06.06.2010 12:22}{thema=}{post}  
В общем-то можно и так записать для достижения цели:  
(Not avArr) = 0    
{/post}{/quote}    
Дим, ты наверное хотел сказать  
(Not avArr) = -1 Then массив пустой

Я сам — дурнее всякого примера! …

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=KuklP}{date=06.06.2010 01:27}{thema=Re: }{post}{quote}{login=The_Prist}{date=06.06.2010 12:22}{thema=}{post}  
В общем-то можно и так записать для достижения цели:  
(Not avArr) = 0    
{/post}{/quote}    
Дим, ты наверное хотел сказать  
(Not avArr) = -1 Then массив пустой{/post}{/quote}Нет, Сергей, я написал ровно то, что хотел.  

  «В общем-то можно и так записать для достижения цели:  
(Not avArr) = 0    
Но все равно придется добавлять Not, чтобы было вроде как понятней(или поменять условия местами).»  

  Это же конструкция сравнения. С нулем как-то смотрится более информативно.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Дим, при (Not avArr) = 0 выдаст, что массив не пустой в обоих случаях.  
при пустом массиве (Not avArr) = -1.  
Проверь.

Я сам — дурнее всякого примера! …

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Да, а Not(-1) как раз и дает 0.

Я сам — дурнее всякого примера! …

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

{quote}{login=KuklP}{date=06.06.2010 02:07}{thema=}{post}Дим, при (Not avArr) = 0 выдаст, что массив не пустой в обоих случаях.  
при пустом массиве (Not avArr) = -1.  
Проверь.{/post}{/quote}Почему?  

  Sub Arr_Initialize()  
   Dim avArr()  
   If (Not avArr) = 0 Then  
       MsgBox «массив пуст и записей в нем не было»  
   Else  
       MsgBox «массив заполнен чем-то»  
   End If  
   ReDim avArr(1): avArr(1) = 1  
   If (Not avArr) = 0 Then  
       MsgBox «массив пуст и записей в нем не было»  
   Else  
       MsgBox «массив заполнен чем-то»  
   End If  
End Sub  

  Вот в этой процедуре получиться, что условия перепутаны. Именно про это я и писал: «Но все равно придется добавлять Not, чтобы было вроде как понятней(или поменять условия местами)»  
Ключевая фраза: поменять условия местами

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Да нет же, Дим(вот я не умею так понятно объяснять как ты)  
Это константы:  
true в Exsel = -1  
False=0  
В твоей конструкции  (Not avArr) = 0 никогда не наступит, ибо для пустого массива  
(Not avArr) = -1  
Для непустого напрмер -2390769 (у меня эта цифра меняется).  
Поэтому твоя программа всегда будет выводить МСГ — «массив заполнен чем-то».

Я сам — дурнее всякого примера! …

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

А, ну да. Чет я сразу не догнал.  
Но первый вариант — (Not Not avArr) = 0 — работает на ура! :-)

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

Все, сдаюсь.

Я сам — дурнее всякого примера! …

 

Извиняюсь, что вклиниваюсь в беседу, но у меня  
первый вариант The_Pristа If (Not Not avArr) = 0 Then  
прошел изумительно.

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

{quote}{login=Егор}{date=06.06.2010 02:36}{thema=}{post}Извиняюсь, что вклиниваюсь в беседу, но у меня  
первый вариант The_Pristа If (Not Not avArr) = 0 Then  
прошел изумительно.{/post}{/quote}  
Егор, это же Вам не понравилось двойное отрицание. Из-за этого и весь этот диспут.  
Прграмма The_Prist работает на ура и без двойного отрицания при  (Not avArr) = -1.

Я сам — дурнее всякого примера! …

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Вообще главная фишка такой проверки в том, что можно проверить даже неинициализированный массив. Т.к. неинициализированный массив при помощи UBound() не проверить — выдаст ошибку.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

{quote}{login=KuklP}{date=06.06.2010 02:43}{thema=Re: }{post}{quote}{login=Егор}{date=06.06.2010 02:36}{thema=}{post}Извиняюсь, что вклиниваюсь в беседу, но у меня  
первый вариант The_Pristа If (Not Not avArr) = 0 Then  
прошел изумительно.{/post}{/quote}  
Егор, это же Вам не понравилось двойное отрицание. Из-за этого и весь этот диспут.  
Прграмма The_Prist работает на ура и без двойного отрицания при  (Not avArr) = -1.{/post}{/quote}  

  мне двойное отрицание не не понравилось, а просто я не знал, что ему может быть  
логичное применение.  
А из вашей беседы я вынес много для себя поучительного, за что вам всем  
очень признателен.

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

Массивы бывают разные.  
В частности, переменная типа Variant тоже может стать массивом,  
и в таком случае (Not Not Arr) = 0 глюканет.  
Пример:  

  Sub Test1()  
 Dim a(), b  
 Debug.Print «a», (Not Not a) = 0  
 Debug.Print «b», (Not Not b) = 0  
 ReDim a(1 To 1)  
 ReDim b(1 To 1)  
 Debug.Print «a1», (Not Not a) = 0  
 Debug.Print «b1», (Not Not b) = 0 ‘ <— выдает ошибку  
End Sub  

  Это потому, что в переменной типа Variant хранится не указатель на массив, а указатель на указатель на массив :-)  

  Поэтому надежнее так:  

  Function IsArrayEmpty(x) As Boolean  
 Dim i&  
 On Error Resume Next  
 i = LBound(x)  
 IsArrayEmpty = Err <> 0  
End Function  

  Sub Test2()  
 Dim a(), b  
 Debug.Print «a», IsArrayEmpty(a)  
 Debug.Print «b», IsArrayEmpty(b)  
 ReDim a(1 To 1)  
 ReDim b(1 To 1)  
 Debug.Print «a1», IsArrayEmpty(a)  
 Debug.Print «b1», IsArrayEmpty(b)  
End Sub

 

В моем массиве каждый элемент это название,состоящее из 2-10 букв.  
(Not Not Arr) = 0 Когда-нибудь глюканет или не глюканет?

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

{quote}{login=ZVI}{date=06.06.2010 03:34}{thema=}{post}Массивы бывают разные.  
Поэтому надежнее так:  
{/post}{/quote}  
Тоже вкусно. Имхо такие фишки как:  
(Not Not avArr) = 0 (The_Prist)  
IsArrayEmpty = Err <> 0 (Ваша ZVI)  
If wsSh.Cells(1, 1).End(xlDown) <> «» (проверка на пустую строку от Слэн)  
и им подобные должны быть в приемах.  
Или, на худой конец, как писал вчера kim:  
«Пора копать землянку макросописателей/(писцев)…». Но это будет не так доступно(разве что беседку, избушку и землянку прилепить в начало форума. Мож как-то к тем 300 советам добавить(это я к модераторам)?

Я сам — дурнее всякого примера! …

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

{quote}{login=Егор}{date=06.06.2010 04:20}{thema=}{post}В моем массиве каждый элемент это название,состоящее из 2-10 букв.  
(Not Not Arr) = 0 Когда-нибудь глюканет или не глюканет?{/post}{/quote}  
Не глюканет, если переменная Arr объявлена так: Dim Arr()  
Глюканет, если переменная Arr не будет никак объявлена, или если будет объявлена так: Dim Arr

 

{quote}{login=ZVI}{date=06.06.2010 04:26}{thema=}{post}{quote}{login=Егор}{date=06.06.2010 04:20}{thema=}{post}В моем массиве каждый элемент это название,состоящее из 2-10 букв.  
(Not Not Arr) = 0 Когда-нибудь глюканет или не глюканет?{/post}{/quote}  
Не глюканет, если переменная Arr объявлена так: Dim Arr()  
Глюканет, если переменная Arr не будет никак объявлена, или если будет объявлена так: Dim Arr{/post}{/quote}  

  Я объявил массив Dim Arr() As Variant в процедуре обработки события в юзерформе, а затем передал его в качестве аргумента в другую процедуру, которая находится в модуле. В модуле делаю проверку на пустойнепустой.  
Так считается , что я его объявил?

 

ZVI

Пользователь

Сообщений: 4328
Регистрация: 23.12.2012

{quote}{login=}{date=06.06.2010 05:00}{thema=Re: }{post}Я объявил массив Dim Arr() As Variant в процедуре обработки события в юзерформе, а затем передал его в качестве аргумента в другую процедуру, которая находится в модуле. В модуле делаю проверку на пустойнепустой.  
Так считается , что я его объявил?{/post}{/quote}  
Dim Arr() As Variant — это то же самое, что Dim Arr()  
Если в объявлении переменной присутствуют круглые скобки, то это явное объявление переменной массива. При этом проблемы с (Not Not Arr) = 0 не будет.  
Если же круглых скобок нет: Dim Arr  
то возникнет указанная проблема с (Not Not Arr) = 0  
Ещё раз — важны именно круглые скобки при объявлении, а As ЛюбойТип — не имеет значения для метода (Not Not Arr) = 0

 

Егор

Гость

#27

06.06.2010 17:55:42

Ясно. Спасибо.

Содержание

  1. Check if Value is in Array using VBA
  2. The VBA Tutorials Blog
  3. VBA Code Library
  4. Check if Value is in Array using VBA
  5. How to use the IsInArray VBA Function
  6. VBA Search for (Find) Value in Array
  7. Searching in a One-Dimensional Array
  8. Find values that match the Filter
  9. Find values that DO NOT match the Filter
  10. Case Sensitive Filters
  11. Option Compare Text
  12. VBA Coding Made Easy
  13. Using a Loop to Search through an array
  14. Searching in a Multi-Dimensional Array
  15. VBA Code Examples Add-in
  16. Проверьте, находится ли значение в массиве или нет с помощью Excel VBA
  17. ОТВЕТЫ
  18. Ответ 1
  19. Ответ 2
  20. Ответ 3
  21. Ответ 4
  22. Ответ 5
  23. Ответ 6
  24. Ответ 7
  25. Check if a value is in an array or not with Excel VBA
  26. 8 Answers 8
  27. Проверка значений массива VBA

Check if Value is in Array using VBA

The VBA Tutorials Blog

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 IsInArray function to see if that number is in an array of strings.

Check if Value is in Array using VBA

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.

How to use the IsInArray VBA Function

When you’re ready to start writing your macros faster (without having to search online for answers) check out our best-selling VBA Cheat Sheets for some powerful automation tricks. For more VBA tips, techniques, and tactics, subscribe to our VBA Insiders email series using the form below.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

VBA Search for (Find) Value in Array

In this Article

This tutorial will demonstrate how to Search for (Find) a Value in an Array in VBA

There are a number of ways you can search for a string in an array – depending on whether the array is a one dimensional or multi-dimensional.

Searching in a One-Dimensional Array

To search for a value in a one-dimensional array, you can use the Filter Function.

The Syntax of the Filter option is a follows

Filter(Source Array, Match as String, [Include as Boolean], [Compare as vbCompareMethod])

The Source Array and the Match as String are required while the Include as Boolean and the Compare as vbCompareMethod are optional. If these are not included they are set to True and vbCompareBinary respectively.

Find values that match the Filter

The second array will hold the values found by the filter. If your UBound values are not -1, then the array has managed to find the value that you were searching for.

You can also see how many times the text appears in the original array.

Find values that DO NOT match the Filter

The [Include as Boolean] option allows you to find how many values in your array which DO NOT match your filter

we have therefore amended this line:

Using this line in the code, would return all the names that do NOT match “Bob”.

Case Sensitive Filters

You will find that the filter is case sensitive by default. This is true for all VBA functions. If you want to search for text that is not case sensitive, you need to amend your code slightly.

Adding vbTextCompare to your filter line will enable your code to find “bob” or “Bob”. If this is omitted, VBA by default uses vbBinaryCompare which will only look for data that is an EXACT match. Notice in the example above, we have left out the [Include as Boolean] argument so True is assumed.

Option Compare Text

Alternatively, you can add the text Option Compare Text to the top of your module – this will make all the functions that you write in that particular module case insensitive.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Using a Loop to Search through an array

Using a loop is a little bit more complicated than using the Filter function. We can create a function that will loop through all the values in the array.

In order to find a part of the text string ie “Bob” instead of “Bob Smith” or “Bob Williams”, we needed to use the Instr Function in the If Statement. This looked in the string returned by the loop from the Array to see if “Bob” was in the string, and as it was in the string, it would return a message box and then Exit the Loop.

Searching in a Multi-Dimensional Array

We also use the loop to search through a multi-dimensional array. Once again, we need to create a function than enables us to loop through all the values in the array, but this time, we also need to loop through each dimension of the array.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Проверьте, находится ли значение в массиве или нет с помощью Excel VBA

У меня есть код ниже, который должен проверять, находится ли значение в массиве или нет.

Если ячейка A1 содержит слово Examples , по какой-то причине обе IsInArray обнаруживают ее как существующую для обоих массивов, когда она должна находить ее только в массиве vars1

Что мне нужно изменить, чтобы сделать мою функцию IsInArray для ее точного соответствия?

ОТВЕТЫ

Ответ 1

Вы можете грубо заставить ее так:

Ответ 2

Ответ 3

Используйте функцию Match() в excel VBA, чтобы проверить, существует ли значение в массиве.

Ответ 4

Хотя это, по сути, просто ответ @Brad, я подумал, что, возможно, стоит включить слегка модифицированную функцию, которая будет возвращать индекс искомого элемента, если он существует в массиве. Если элемент отсутствует в массиве, он возвращает -1 .

Вывод этого можно проверить так же, как функцию «in string», If InStr(. ) > 0 Then , поэтому я сделал небольшую тестовую функцию под ней в качестве примера.

Затем я пошел немного за борт и выделил один для двухмерных массивов, потому что, когда вы генерируете массив на основе диапазона, он обычно в этой форме.

Он возвращает один вариантный массив измерений только с двумя значениями, два индекса массива используются в качестве входных данных (при условии, что значение найдено). Если значение не найдено, возвращается массив (-1, -1) .

Вот картина данных, которые я настроил для теста, а затем тест:

Ответ 5

Приведенная ниже функция возвращает 0, если совпадения нет, и положительное целое в случае совпадения:

Function IsInArray(stringToBeFound As String, arr As Variant) As Integer IsInArray = InStr(Join(arr, «»), stringToBeFound) End Function ______________________________________________________________________________

Примечание: функция сначала объединяет содержимое всего массива со строкой, используя ‘Join’ (не уверен, использует ли метод join внутреннее или нет циклическое выполнение), а затем проверяет наличие macth внутри этой строки, используя InStr.

Ответ 6

Я хотел бы предоставить еще один вариант, который должен быть и производительным и мощным, потому что

  • он не использует иногда более медленный Match )
  • поддерживает String , Integer , Boolean и т.д. (не String -only)
  • возвращает индекс искомого элемента
  • поддерживает nth-вхождение

используйте это так:

Ответ 7

Вы хотите проверить, существует ли Примеры в Range ( «A1» ). Значение Если это не удается, проверьте правильность Пример. Я думаю, что mycode будет работать идеально. Пожалуйста, проверьте.

Источник

Check if a value is in an array or not with Excel VBA

I’ve got some code below, that is supposed to be checking if a value is in an Array or not.

If the cell A1 contains the word Examples for some reason both of the IsInArray detects it as existing for both Arrays when it should only find it existing in the vars1 array

What do I need to change to make my IsInArray function to make it an exact match?

8 Answers 8

You can brute force it like this:

arrays through IsInArray , in total all of them added up comes to 501 array items at the moment. It will eventually become bigger/more of them.

I searched for this very question and when I saw the answers I ended up creating something different (because I favor less code over most other things most of the time) that should work in the vast majority of cases. Basically turn the array into a string with array elements separated by some delimiter character, and then wrap the search value in the delimiter character and pass through instr.

And you’d execute the function like this:

Use Match() function in excel VBA to check whether the value exists in an array.

The below function returns ‘0’ if there is no match and a ‘positive integer’ in case of matching:

Note: the function first concatenates the entire array content to a string using ‘Join’ (not sure if the join method uses looping internally or not) and then checks for a match within this string using InStr .

I would like to provide another variant that should be both performant and powerful, because

  • it does not use the sometimes slower Match )
  • supports String , Integer , Boolean etc. (not String -only)
  • returns the index of the searched-for item
  • supports nth-occurrence

use it like this:

While this is essentially just @Brad’s answer again, I thought it might be worth including a slightly modified function which will return the index of the item you’re searching for if it exists in the array. If the item is not in the array, it returns -1 instead.

The output of this can be checked just like the «in string» function, If InStr(. ) > 0 Then , so I made a little test function below it as an example.

Then I went a little overboard and fleshed out one for two dimensional arrays because when you generate an array based on a range it’s generally in this form.

It returns a single dimension variant array with just two values, the two indices of the array used as an input (assuming the value is found). If the value is not found, it returns an array of (-1, -1) .

Here’s a picture of the data that I set up for the test, followed by the test:

Источник

Проверка значений массива VBA

Я пытаюсь убедиться, что массив, который я построил, имеет значения, которые я ожидаю.

Предполагается, что массив карт заполняет массив Shoe.

Когда я подсчитываю значения массива, я получаю ожидаемый 104, но когда я вставляю значения в лист excel, заполняется только 13 ячеек.

Есть ли простой способ проверить содержимое массива?

Вы можете использовать Join :

в непосредственном окне. Кроме того, если вы используете отладчик для пошагового выполнения кода, в окне Locals вы можете расширить имя массива и проверить отдельные элементы.

На редактирование: расширение на этом последнем пункте. Если в редакторе VBA вы выбираете View → Locals Window и устанавливаете точку останова (щелкая слева от строки) перед строкой кода, куда вы отправляете shoe на лист, вы должны увидеть что-то вроде:

Если вы запустите сабвуфер, он перейдет в режим прерывания следующим образом:

Тогда, если вы расширите shoe вы увидите:

Этого достаточно, чтобы показать, что вы не инициализируете shoe после индекса 13. Другие опубликовали ответы, показывающие источник этой ошибки – но это действительно важный навык, чтобы иметь возможность, как ваш вопрос, проверить значения массива,

При редактировании Join плохо работает с массивами, которые не являются ни Variant ни String . Если у вас есть массив, который объявлен как, например,

вы могли бы сначала запустить его через следующую функцию:

Тогда Join(ToVariant(Directions), «, «) будет работать как положено.

Вы только заселяете первые 13 значений здесь:

Вы захотите зациклировать это 8 раз, чтобы получить 104

Что ты пытаешься сделать? Заполните ботинок с 104 карточками (по 8 штук)? Если это так, я бы сделал это с помощью метода split/join. Приятно размещать код для этого, если вам нужно. Идея заключается в создании строки в цикле для добавления объединенного массива карт столько раз, сколько вам нужно (в этом случае 8), а затем разделить это на обувь.

Вы гомогенизировали карты, отбрасывая костюмы, но их все равно нужно добавлять в циклы, чтобы получить правильное количество карт для каждой колоды.

Я включил дополнительную строку кода, которая включает в себя костюм каждой карты по мере ее создания. Может быть, лучше включить это для целей отладки, пока вы не получите правильное формирование обуви, а затем отбросьте костюм после его запуска.

Источник

In this Article

  • Searching in a One-Dimensional Array
    • Find values that match the Filter
    • Find values that DO NOT match the Filter
    • Case Sensitive Filters
    • Option Compare Text
  • Using a Loop to Search through an array
  • Searching in a Multi-Dimensional Array

This tutorial will demonstrate how to Search for (Find) a Value in an Array in VBA

There are a number of ways you can search for a string in an array – depending on whether the array is a one dimensional or multi-dimensional.

Searching in a One-Dimensional Array

To search for a value in a one-dimensional array, you can use the Filter Function.

Dim z As Variant
'filter the original array
  z = Filter(Array, String, True, vbCompareBinary)

The Syntax of the Filter option is a follows

Filter(Source Array, Match as String, [Include as Boolean], [Compare as vbCompareMethod])

The Source Array and the Match as String are required while the Include as Boolean and the Compare as vbCompareMethod are optional.  If these are not included they are set to True and vbCompareBinary respectively.

Find values that match the Filter

Sub FindBob()
   'Create Array
   Dim strName() As Variant
   strName() = Array("Bob Smith", "John Davies", "Fred Jones", "Steve Jenkins", "Bob Williams")
   
   'declare a variant to store the filter data in
   Dim strSubNames  As Variant

  'filter the original array
   strSubNames = Filter(strName, "Bob")

   'if you UBound value is greater than -1, then the value has been found
   If UBound(strSubNames ) > -1 Then MsgBox ("I found Bob")
End Sub

The second array will hold the values found by the filter.  If your UBound values are not -1, then the array has managed to find the  value that you were searching for.

You can also see how many times the text appears in the original array.

Sub CountNames()
   'Create array
   Dim strName() As Variant
   strName() = Array("Bob Smith", "John Davies", "Fred Jones", "Steve Jenkins", "Bob Williams")

  'declare an array to store the filter data in
   Dim strSubNames As Variant

   'filter the original array
   strSubNames = Filter(strName, "Bob")

   'if you add 1 to the UBound value, we will get the number of times the text appears
   Msgbox  UBound(strSubNames) + 1 & " names found." 
End Sub

Find values that DO NOT match the Filter

The [Include as Boolean] option allows you to find how many values in your array which DO NOT match your filter

Sub CountExtraNames() 
  'create array
  Dim strName() As Variant 
  strName() = Array("Bob Smith", "John Davies", "Fred Jones", "Steve Jenkins", "Bob Williams") 

  'declare an array to store the filter data in 
  Dim strSubNames As Variant 

  'filter the original array 
  strSubNames = Filter(strName, "Bob", False) 

  'if you add 1 to the UBound value, we will get the number of times the text appears 
  Msgbox  UBound(strSubNames) + 1 & " names found." 
End Sub

we have therefore amended this line:

strSubNames = Filter(strName, "Bob")

with this line:

strSubNames = Filter(strName, "Bob", False)

Using this line in the code, would return all the names that do NOT match “Bob”.

vba find array msgbox

Case Sensitive Filters

You will find that the filter is case sensitive by default.  This is true for all VBA functions.  If you want to search for text that is not case sensitive, you need to amend your code slightly.

z = Filter(strName, "bob",, vbTextCompare)

Adding vbTextCompare to your filter line will enable your code to find “bob” or “Bob”.  If this is omitted, VBA by default uses vbBinaryCompare which will only look for data that is an EXACT match.  Notice in the example above, we have left out the [Include as Boolean] argument so True is assumed.

Option Compare Text

Alternatively, you can add the text Option Compare Text to the top of your module – this will make all the functions that you write in that particular module case insensitive.

vba find array option compare text

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Using a Loop to Search through an array

Using a loop is a little bit more complicated than using the Filter function.  We can create a function that will loop through all the values in the array.

Sub LoopThroughArray()
  'create array
  Dim strName() As Variant 
  strName() = Array("Bob Smith", "John Davies", "Fred Jones", "Steve Jenkins", "Bob Williams") 

Dim strFind as string 
strFind = "Bob"

Dim i As Long
'loop through the array
   For i = LBound(strName, 1) To UBound(strName, 1)
       If InStr(strName(i), strFind) > 0 Then
          MsgBox "Bob has been found!"
          Exit For
       End If
    Next i
End Sub

In order to find a part of the text string ie “Bob” instead of “Bob Smith” or “Bob Williams”, we needed to use the Instr Function in the If Statement.  This looked in the string returned by the loop from the Array to see if “Bob” was in the string, and as it was in the string, it would return a message box and then Exit the Loop.

Searching in a Multi-Dimensional Array

We also use the loop to search through a multi-dimensional array.  Once again, we need to create a function than enables us to loop through all the values in the array, but this time, we also need to loop through each dimension of the array.

Function LoopThroughArray()
   Dim varArray() As Variant
   Dim strFind As String
   strFind = "Doctor"
'declare the size of the array
   ReDim varArray(1, 2)
'initialise the array
   varArray(0, 0) = "Mel Smith"
   varArray(0, 1) = "Fred Buckle"
   varArray(0, 2) = "Jane Eyre"
   varArray(1, 0) = "Accountant"
   varArray(1, 1) = "Secretary"
   varArray(1, 2) = "Doctor"
'declare variables for the loop
   Dim i As Long, j As Long
'loop for the first dimension
   For i = LBound(varArray, 1) To UBound(varArray, 1)
'loop for the second dimension
      For j = LBound(varArray, 2) To UBound(varArray, 2)
'if we find the value, then msgbox to say that we have the value and exit the function
         If varArray(i, j) = strFind Then
            MsgBox "Doctor has been found!"
            Exit Function
         End If
      Next j
   Next i
End Function

Completing remark to Jimmy Pena’s accepted answer

As SeanC points out, this must be a 1-D array.

The following example call demonstrates that the IsInArray() function cannot be called only for 1-dim arrays,
but also for «flat» 2-dim arrays:

Sub TestIsInArray()
    Const SearchItem As String = "ghi"
    Debug.Print "SearchItem = '" & SearchItem & "'"
    '----
    'a) Test 1-dim array
    Dim Arr As Variant
    Arr = Split("abc,def,ghi,jkl", ",")
    Debug.Print "a) 1-dim array " & vbNewLine & "   " & Join(Arr, "|") & " ~~> " & IsInArray(SearchItem, Arr)
    '----
    
        '//quick tool to create a 2-dim 1-based array
        Dim v As Variant, vals As Variant                                       
        v = Array(Array("abc", "def", "dummy", "jkl", 5), _
                  Array("mno", "pqr", "stu", "ghi", "vwx"))
        v = Application.Index(v, 0, 0)  ' create 2-dim array (2 rows, 5 cols)
    
    'b) Test "flat" 2-dim arrays
    Debug.Print "b) ""flat"" 2-dim arrays "
    Dim i As Long
    For i = LBound(v) To UBound(v)
        'slice "flat" 2-dim arrays of one row each
        vals = Application.Index(v, i, 0)
        'check for findings
        Debug.Print Format(i, "   0"), Join(vals, "|") & " ~~> " & IsInArray(SearchItem, vals)
    Next i
End Sub
Function IsInArray(stringToBeFound As String, Arr As Variant) As Boolean
'Site: https://stackoverflow.com/questions/10951687/how-to-search-for-string-in-an-array/10952705
'Note: needs a "flat" array, not necessarily a 1-dimensioned array
  IsInArray = (UBound(Filter(Arr, stringToBeFound)) > -1)
End Function

Results in VB Editor’s immediate window

SearchItem = 'ghi'
a) 1-dim array 
   abc|def|ghi|jkl ~~> True
b) "flat" 2-dim arrays 
   1          abc|def|dummy|jkl|5         False
   2          mno|pqr|stu|ghi|vwx         True

Понравилась статья? Поделить с друзьями:
  • Vba excel проверка если значение в ячейке
  • Vba excel присвоить имя диапазону
  • Vba excel проверка дата или нет
  • Vba excel приостановить выполнение макроса
  • Vba excel проверка данных список