Excel vba if array is not empty

When a list or collection of items that are the same data type are stored in continuous memory locations, we call it an array. Arrays are useful objects that are widely used in software development to organize data. Some real examples of where you might use them might include:

  1. Online games, like chess, make use of two dimensional arrays.
  2. An ECG waveform is a realtime example of array usage.

I’ll show you a couple array examples, then we’ll get into how to check if one is empty.

Sub array_demo()

'Declaration of array variable
Dim arr() As String

'Defining length of array
ReDim arr(8)

For i = 0 To 8
    'Allocate data for each array item through a loop
    arr(i) = Cells(i + 2, 1).Value
    
    'Print each item
    Debug.Print arr(i)
Next

End Sub

Output in Excel for array with wonders of the world

Here is another example that creates an array as a result of using the Split function.

Sub array_split_demo()

'list of days in a string separated by a single space
days_string = "sunday monday tuesday wednesday thursday friday saturday"

'splitting the string into an array using a delimiter
weekdays = Split(days_string, " ")

'printing them all
For i = LBound(weekdays) To UBound(weekdays)
Debug.Print weekdays(i)
Next

End Sub

The above code prints a list of days while iterating through the array in that was created when the string was split and stored.

Types of arrays

In VBA arrays can either be static or dynamic.

Static arrays

The size of the array is fixed and cannot be changed.

Dynamic arrays

The size of the array is not fixed and can be modified based on your requirements.

Check if an array is empty or contains data

In VBA, unless we first define the size of an array, we cannot use the Lbound() and UBound functions. It will throw an error. So, we need to use the Redim keyword and define a size as soon as we declare an array.

Also there isn’t a specific function that can validate the existence of data in an array. So, we have to make use pf other available functions, along with some logic, to determine if an array is empty or not.

Below are a few methods you can utilize.

Join function

Just like how we used the split function to split a string into an array, a Join function can be used to concatenate all elements of an array into a single string.

Syntax:

Join ( <source array> , [ < Delimiter > ] )

Where

Source array is the name of the array whose elements need to be joined.

Delimiter is the character that is going to be placed between the concatenation of every two elements while joining the array elements. This is an optional parameter and if it’s not provided, a space “ “ is used by default.

If a zero length string “” is provided as a delimiter, the joining happens without inserting any characters during concatenation.

For example:

Sub join_arraydemo()

' Join together the strings "Orange", "Apple" and "Mango".
Dim all_fruits As String
Dim fruits(0 To 2) As String

'assign values for all fruits
fruits(0) = "Orange"
fruits(1) = "Apple"
fruits(2) = "Mango"

'Join using the built-in function
all_fruits = Join(fruits)

' The variable all_fruits is now set to "Orange Apple Mango"
Debug.Print all_fruits
End Sub

So, first all the elements of the array are concatenated using the Join function, then the resulting string’s length can be checked to check if the array is empty or not.

The below piece of code can be added to the above code sample to notify you if the array is empty or not.

If Len(all_fruits) &amp;amp;amp;gt; 0 Then
Debug.Print "fruits array is not empty"
Else
Debug.Print "Fruits array is empty"
End If

In short, we can use the below line to achieve the same results.

If Len(Join(all_fruits)) &amp;amp;amp;gt; 0 Then

Iterate through all the items in the array

Using a For loop, we can iterate through each element in an array to validate whether the array has some data or it is completely empty. Here’s a ready to use function for you.

Function IsEmptyArray(arr)

'a normal flag variable
flag = 0

'loop to check if atleast one element of te array has data
For i = LBound(arr) To UBound(arr)
If IsEmpty(arr(i)) = False Then
    Debug.Print "The array has data"
    flag = 1
    Exit For
End If
Next

'Check if flag value has changed because data is present
If flag = 0 Then
    Debug.Print "The array is empty"
End If

End Function

UBound function + bypass an error

Because an error will be thrown if we use the Ubound or Lbound function on an empty array, we are going to use the “On Error Resume Next” statement and catch the error number to test if the array is empty. Here the array is considered empty if it doesn’t have a size defined. I created a function to help you better understand and use the code.

Sub array_check_demo()

'Declaration of array variable
Dim arr() As Variant

'The array should be empty now
Debug.Print Is_Var_Array_Empty(arr)

'Defining length of array
ReDim arr(8)

'The array has a size . So, as per this logic, it is not empty
Debug.Print Is_Var_Array_Empty(arr)
'We check if the array is empty before assigning values

'Assign values to array elements
For i = 0 To 8
    'Allocate data for each array item through a loop
    arr(i) = Cells(i + 2, 1).Value
Next

'validate if array is empty again
Debug.Print Is_Var_Array_Empty(arr)

End Sub
Function Is_Var_Array_Empty(arr_var As Variant)

Dim p As Integer

On Error Resume Next
    p = UBound(arr_var, 1)
If Err.Number = 0 Then
    Is_Var_Array_Empty = False
Else
    Is_Var_Array_Empty = True
End If

End Function

Results from testing if array is empty using ubound/lbound

StrPtr() function for a byte array

A byte array is nothing but a series or characters. A string can directly be assigned to a byte array. Two elements of an array are used to allocate space for a character from a string. The below code should help you understand further.

Sub byte_array_demo()

'declare a byte array and a string
Dim arr1() As Byte
Dim samplestr As String

'initiate the string
samplestr = "Coffee"

'Check if the array is empty. StrPtr(&amp;amp;amp;lt;arrname&amp;amp;amp;gt;) would return 0 if the array is empty.
Debug.Print StrPtr(arr1) = 0

'allocate the string directly to the byte array
arr1() = samplestr

'View what has been stored in the array
For i = LBound(arr1) To UBound(arr1)
Debug.Print arr1(i)
Next

'Check if the array is empty. StrPtr(&amp;amp;amp;lt;arrname&amp;amp;amp;gt;) would return 0 if the array is empty.
Debug.Print StrPtr(arr1) = 0

End Sub

Explaining the output:

Initially the array is empty , so StrPtr(arr1) returns true.

Ascii value of “C” is 67

Ascii null character

Ascii value of “o” is 111

Ascii null character

Ascii value of “f” is 102

Ascii null character

Ascii value of “f” is 102

Ascii null character

Ascii value of “e” is 101

Ascii null character

Ascii value of “e” is 101

Ascii null character

Finally the array is not empty , so StrPtr(arr1) returns false.

Results from checking array using strptr function.

Conclusion

In VBA, other than StrPtr() function for byte arrays , there are no direct methods to find if an array is empty or not. However our best friend, Magical VBA, offers flexible functions that can be combined with your own logic to check the size of an array or the existence or non-existence of data in an array of any datatype.

The meaning of “EMPTY” here lies with the user. It could either be an array that does not have a size defined or an array that has a specific size but no data in it.

Of the above methods, I recommend just grabbing a user-defined function that you can easily use to check if an array is empty or not.

If you’re looking to see how to check if a cell is empty, check out our article here.

Tagged with: Arrays, Concatenating, Lbound, Loop, redim, Size, Split, Strings, StrPtr, Ubound, VBA

When dealing with arrays in VBA, you must realize that there are two different types, and that is static and dynamic.

Static arrays are of a fixed size, we declare them only once. Dynamic arrays can be changed, or re-dimensioned. Now, until they do not have assigned values, dynamic arrays are empty. To check if our array is empty or not, we need to create a separate function that will check if the array is empty or not.

We will show how to do it in the example below.

Creating a Function to Check if an Array is Empty in VBA

The first thing that we need to do if the array is empty is to create a function that will do this job for us. For this, we need to open our VBA module. While in the Excel file, click on ALT + F11, and then right-click on the left window that appears, go to Insert >> Module:

Once there, this is the function that we will have to input:

Function Array_Empty(var As Variant)

    ‘Declaring the variable

    Dim k As Integer

    On Error Resume Next

    ‘setting the variable

    k = UBound(var, 1)

    ‘If formula

    If Err.Number = 0 Then

        Array_Empty = FALSE

    Else

        Array_Empty = TRUE

    End If

End Function

And this is what it looks like in the module:

This function, called Array_Empty with one parameter (var as a variant) will check every value in our array and give us the results: 1) False if any value if all of the values in our array are populated and 2) True if our array is empty.

Once we have our function in place, we are ready for the code. This is what our code will be:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Sub CheckingIfArrayIsEmpty()

    ‘Declaring the array variable

    Dim a() As Variant

    ‘The array will be empty as it has no assigned values

    Range(«b2»).Value = Array_Empty(a)

    ‘Defining length of array

    ReDim a(6)

    Range(«b3»).Value = Array_Empty(a)

    ‘We check if the array is empty before assigning values

    ‘Assigning values

    For i = 0 To 6

        ‘We will allocate values with For Next Loop

        a(i) = Cells(i + 2, 1).Value

    Next

    ‘check if the array is empty at this point

    Range(«b4»).Value = Array_Empty(a)

End Sub

For the first thing in our code, we will declare the variable:

In this stage, our array will be empty, as there are no values assigned to it, which is the exact thing we wrote in the comment section of our code as well. We will make the table in our worksheet, to check the values of our array at any given moment:

The next line of our code is very important:

Range(«b2»).Value = Array_Empty(a)

In this part, we are determining the value of cell B2 to be the current value of our array based on the result of our function Array_Empty. We can only have two values, as we said- TRUE (if the array is empty) and FALSE (if it is not).

In our case, for the first check of the array, we should get the result TRUE, as our array is empty.

When we step through our code by pressing F8 on our keyboard (we do so until we reach the line of the code ReDim a(6)) we will get the following results in the worksheet:

In the next part of the code:

ReDim a(6)

Range(«b3»).Value = Array_Empty(a)

We use ReDim to re-dimension our array and to define its length. Our array will have six values. Now, at this point, we are not sure if it is empty or not, as we still did not assign any values to it. We will step through our code one more time, and this is what we will end up with:

This means that our array will not be empty, i.e. it will not be considered as such when re-dimensioned, even when it does not have certain values assigned to it.

For the final part of our code, we will assign some values to our array with For Next Loop and then check if our array is empty or not (we will see the results in cell B4).

For i = 0 To 6

    a(i) = Cells(i + 2, 1).Value

Next

Range(«b4»).Value = Array_Empty(a)

When we step through this part of the code, we get this picture:

This means, of course, that our array is not empty when it has values assigned to it.

For every part of the code, we are calling our function to check if our array is empty or not. Use the function described in the first part and alternate your code as you please, to achieve the same results.

Post Views: 1,665

  • #1

These if … then statements are getting the wrong results in my opinion. The first is returning the value ‘false’ when it should be ‘true’. The second returns the right value. The third and fourth return an error.

Code:

Sub empty_array()


Dim arr1() As Variant


If IsEmpty(arr1) Then
MsgBox "hey"
End If


ReDim arr1(1)
arr1(1) = "hey"


If IsEmpty(arr1) Then
MsgBox "hey"
End If


If IsError(UBound(arr1)) Then
MsgBox "hey"
End If


If IsError(Application.match("*", (arr1), 0)) Then
MsgBox "hey"
End If


End Sub

Этот код не выполняет то, что вы ожидаете:

If Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

Если вы передадите пустую строку ("") или vbNullString в Dir, она вернет имя первого файла в текущем пути к каталогу (путь, возвращаемый CurDir$). Итак, если SigString пусто, ваше условие If будет оцениваться как True, потому что Dir вернет непустую строку (имя первого файла в текущем каталоге), а GetBoiler будет называется. И если SigString пуст, вызов fso.GetFile завершится с ошибкой.

Вы должны либо изменить свое условие, чтобы проверить, что SigString не пусто, либо использовать FileSystemObject.FileExists вместо Dir для проверки наличия файла. Dir сложно использовать именно потому, что он делает то, чего вы не ожидаете от него. Лично я использовал бы Scripting.FileSystemObject над Dir, потому что нет смешного бизнеса (FileExists возвращает True, если файл существует, и, ну, False, если он этого не делает). Что еще, FileExists выражает намерение вашего кода намного ясно, чем Dir.

Способ 1. Убедитесь, что SigString не является пустым первым

If SigString <> "" And Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

Метод 2: используйте метод FileSystemObject.FileExists

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")

If fso.FileExists(SigString) Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

Содержание

  1. Как проверить наличие пустого массива в макросе vba
  2. 22 ответа
  3. check if array is empty (vba excel)
  4. 11 Answers 11
  5. Как проверить наличие пустого массива в макросе vba [дубликат]
  6. 23 ответы
  7. How to check for empty array in vba macro [duplicate]
  8. 22 Answers 22
  9. Excel Visual Basic — определить, если диапазон пуст
  10. 6 ответов

Как проверить наличие пустого массива в макросе vba

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

Здесь, если массив FileNamesList пуст, GetBoiler(SigString) не должен вообще вызываться. Когда массив FileNamesList пуст, SigString также пуст и вызывает функцию GetBoiler() с пустой строкой. Я получаю сообщение об ошибке в строке

так как sFile пусто. Любой способ избежать этого?

22 ответа

Как вы имеете дело со строковым массивом, считаете ли вы Join?

Go с тройным отрицательным:

В VB по какой-либо причине Not myArray возвращает указатель SafeArray. Для неинициализированных массивов возвращается -1. Вы можете использовать Not для XOR с -1, возвращая тем самым нуль, если хотите.

Если вы проверите функцию массива, она будет работать для всех границ:

Я вижу похожие ответы здесь. но не мои.

Вот как я, к сожалению, собираюсь разобраться с этим. Мне нравится подход len (join (arr)) > 0, но он не будет работать, если массив был массивом emptystrings.

Я просто вставляю под кодом великого Чипа Пирсона. Это работает. Здесь его страница о функциях массива.

Надеюсь, это поможет.

При написании VBA это предложение в моей голове: «Может быть так просто, но. «

Вот что я принял это:

Этот код не выполняет то, что вы ожидаете:

Если вы передадите пустую строку ( «» ) или vbNullString в Dir , она вернет имя первого файла в текущем пути к каталогу (путь, возвращаемый CurDir$ ). Итак, если SigString пусто, ваше условие If будет оцениваться как True , потому что Dir вернет непустую строку (имя первого файла в текущем каталоге), а GetBoiler будет называется. И если SigString пуст, вызов fso.GetFile завершится с ошибкой.

Вы должны либо изменить свое условие, чтобы проверить, что SigString не пусто, либо использовать FileSystemObject.FileExists вместо Dir для проверки наличия файла. Dir сложно использовать именно потому, что он делает то, чего вы не ожидаете от него. Лично я использовал бы Scripting.FileSystemObject над Dir , потому что нет смешного бизнеса ( FileExists возвращает True , если файл существует, и, ну, False , если он этого не делает). Что еще, FileExists выражает намерение вашего кода намного ясно, чем Dir .

Способ 1. Убедитесь, что SigString не является пустым первым

Источник

check if array is empty (vba excel)

These if . then statements are getting the wrong results in my opinion. The first is returning the value ‘false’ when it should be ‘true’. The fourth returns the right value. The second and third return an error.

11 Answers 11

Arr1 becomes an array of ‘Variant’ by the first statement of your code:

Array of size zero is not empty, as like an empty box exists in real world.

If you define a variable of ‘Variant’, that will be empty when it is created.

Following code will display «Empty».

Adding into this: it depends on what your array is defined as. Consider:

So, what can we do? In VBA, we can see if we can trigger an error and somehow handle it, for example

But this is really clumsy. A nicer solution is to declare a boolean variable (a public or module level is best). When the array is first initialised, then set this variable. Because it’s a variable declared at the same time, if it loses it’s value, then you know that you need to reinitialise your array. However, if it is initialised, then all you’re doing is checking the value of a boolean, which is low cost. It depends on whether being low cost matters, and if you’re going to be needing to check it often.

The last thing you can do is create a function; which in this case will need to be dependent on the clumsy on error method.

Источник

Как проверить наличие пустого массива в макросе vba [дубликат]

Я хочу проверить наличие пустых массивов. Google дал мне разные решения, но ничего не помогло. Может я неправильно их применяю.

Здесь если FileNamesList массив пуст, GetBoiler(SigString) не должны звонить вообще. Когда FileNamesList массив пуст, SigString также пусто, и это вызывает GetBoiler() функция с пустой строкой. Я получаю сообщение об ошибке в строке

с sFile пустой. Есть ли способ избежать этого?

Узнать подробности modArraySupport, полезный набор процедур от Чипа Пирсона для поддержки обработки массивов. IsArrayEmpty делает что хочешь. — Jean-François Corbett

Если TypeName (FileNamesList) = «Empty», то — tsolina

23 ответы

Когда вы имеете дело со строковым массивом, рассматривали ли вы возможность соединения?

да это коротко. но потенциально он делает много ненужной работы. — Питер

@VBOG Хотите уточнить? — Fionnuala

@Remou. Не FileNamesList массив? Разве вы не должны использовать Ubound вместо Len? — user2491612

@VBOG Нет, потому что JOIN только что создал строку из массива. — Fionnuala

Загвоздка в том, что это не работает, если у меня есть массив пустых строк . На самом деле это не говорит мне, был ли массив инициализирован. — Профекс

Сделайте тройной минус:

В VB по какой-либо причине Not myArray возвращает указатель SafeArray. Для неинициализированных массивов возвращается -1. Вы можете Not это для XOR с -1, таким образом возвращая ноль, если хотите.

Создан 28 июля ’16, 11:07

Замечательное решение. Никогда не знал об этом взломе. Ваше здоровье! — гиперс

Хороший трюк, +1 от меня, но, к сожалению, я не могу использовать это как часть функции, так как получаю ошибку времени выполнения 13, несоответствие типа Function isArrayInitialized2(Arr As Variant) As Boolean If (Not Arr) = -1 Then isArrayInitialized2 = False Else isArrayInitialized2 = True End Function — нкацар

@nkatsar вам нужно передать Arr как Arr () — user425678

Если вы протестируете функцию массива, она будет работать для всех границ:

ответ дан 12 мар ’09, в 20:03

Неплохо, но примерь arr определяется как это Dim arr() As String : arr = Split(«») : Debug.Print IsVarArrayEmpty(arr) . Это возвращается False , но, судя по всему, arr is пустой массив (или как его еще назвать?), как ни странно, UBound(arr)=-1 и LBound(arr)=0 . Эта проблема решена в Чипе Пирсоне. ИсАррайПустой. Вот почему я связался с ним в своем комментарии к вопросу. — Жан-Франсуа Корбетт

К сожалению, существует неопределенный массив, когда UBound выдает ошибку. Также есть пустой массив, в котором длина находится, как и в любом другом случае: UBound (-1) — LBound (0) = 0 — Эндрю Деннисон

Привет, если вы находитесь на базе 0, ваш массив может добавить один элемент с индексом = 0. Это работает, если вы не устанавливаете массив, но не используете redim arr (0). В этом случае ваше решение не работает. Вам нужно проверить, если Ubound (arr) = 0 и len (Join (arr)) = 0. Это часть ответа @BBQ Chef — ГеоСтоунМартен

Я вижу здесь похожие ответы . но не мои .

Вот как я, к сожалению, собираюсь с этим справиться . Мне нравится подход len (join (arr))> 0, но он не сработал бы, если бы массив был массивом пустых строк .

Когда я пишу VBA, у меня в голове возникает такая фраза: «Могло бы быть так просто, но . »

Вот для чего я его адаптировал:

Есть более короткие обсуждения проверки массива на пустоту в сборке. Это просто смешно. — Андре Фрателли

@ André Fratelli Как бы я хотел проголосовать за ваш комментарий — GLRoman

Этот код не делает того, что вы ожидаете:

Если вы передадите пустую строку ( «» ) Или vbNullString в Dir , он вернет имя первого файла в текущем пути к каталогу (путь, возвращаемый CurDir$ ). Так что если SigString пусто, твой If состояние будет оцениваться как True , так как: Dir вернет непустую строку (имя первого файла в текущем каталоге), а GetBoiler будет называться. И если SigString пусто, вызов fso.GetFile не удастся.

Вам следует либо изменить свое состояние, чтобы убедиться, что SigString не пусто, или используйте FileSystemObject.FileExists метод вместо Dir для проверки, существует ли файл. Dir сложно использовать именно потому, что он делает то, чего от него нельзя ожидать. Лично я бы использовал Scripting.FileSystemObject за Dir потому что нет смешного бизнеса ( FileExists Возвращает True если файл существует, и, ну, False если нет). Более того, FileExists выражает намерение вашего кода намного яснее, чем Dir .

Метод 1. Убедитесь, что SigString не пусто сначала

Метод 2: используйте FileSystemObject.FileExists метод

Я просто вставляю ниже код великого Чипа Пирсона. Это работает очаровательно.
Вот его страница о функциях массива.

Надеюсь, это поможет.

ответ дан 08 мая ’18, 22:05

RE: «В редких случаях, когда я не могу надежно воспроизвести, Err.Number будет равен 0 для нераспределенного пустого массива»; это происходит, когда пустой массив создается с помощью arr = array () — vbAdder

Auth был ближе всего, но его ответ выдает ошибку несоответствия типа.

Что касается других ответов, вам следует избегать использования ошибки для проверки условия, если вы можете, потому что, по крайней мере, это усложняет отладку (что, если что-то еще вызывает эту ошибку).

Источник

How to check for empty array in vba macro [duplicate]

I want to check for empty arrays. Google gave me varied solutions but nothing worked. Maybe I am not applying them correctly.

Here if FileNamesList array is empty, GetBoiler(SigString) should not get called at all. When FileNamesList array is empty, SigString is also empty and this calls GetBoiler() function with empty string. I get an error at line

since sFile is empty. Any way to avoid that?

22 Answers 22

Go with a triple negative:

In VB, for whatever reason, Not myArray returns the SafeArray pointer. For uninitialized arrays, this returns -1. You can Not this to XOR it with -1, thus returning zero, if you prefer.

As you are dealing with a string array, have you considered Join?

If you test on an array function it’ll work for all bounds:

I see similar answers on here. but not mine.

This is how I am unfortunatley going to deal with it. I like the len(join(arr)) > 0 approach, but it wouldn’t work if the array was an array of emptystrings.

When writing VBA there is this sentence in my head: «Could be so easy, but. «

Here is what I adopted it to:

This code doesn’t do what you expect:

If you pass an empty string ( «» ) or vbNullString to Dir , it will return the name of the first file in the current directory path (the path returned by CurDir$ ). So, if SigString is empty, your If condition will evaluate to True because Dir will return a non-empty string (the name of the first file in the current directory), and GetBoiler will be called. And if SigString is empty, the call to fso.GetFile will fail.

You should either change your condition to check that SigString isn’t empty, or use the FileSystemObject.FileExists method instead of Dir for checking if the file exists. Dir is tricky to use precisely because it does things you might not expect it to do. Personally, I would use Scripting.FileSystemObject over Dir because there’s no funny business ( FileExists returns True if the file exists, and, well, False if it doesn’t). What’s more, FileExists expresses the intent of your code much clearly than Dir .

Method 1: Check that SigString is non-empty first

Источник

Excel Visual Basic — определить, если диапазон пуст

Я не знаю, возможно ли это, но я хочу проверить, свободен ли диапазон в Excel. Итак, как мне написать, если:

Пусто в коде VBA?

6 ответов

Нашел решение из комментариев, которые я получил.

IsEmpty возвращает True, если переменная не инициализирована или явно установлена ​​в Пустое; в противном случае он возвращает False. False всегда возвращается, если выражение содержит более одной переменной. IsEmpty только возвращает значимую информацию для вариантов. (https://msdn.microsoft.com/en-us/library/office/gg264227.aspx). Поэтому вы должны проверять каждую ячейку отдельно:

Конечно, здесь больше кода, чем в решении с функцией CountA, которые подсчитывают не пустые ячейки, но GoTo может перехватывать петли, если найдена хотя бы одна непустая ячейка и быстрее выполняет ваш код, особенно если диапазон большой, и вам нужно обнаружить Это дело. Также этот код для меня легче понять, что он делает, чем с функцией Excel CountA, которая не является функцией VBA.

Из опыта, который я только что узнал, вы могли бы сделать:

Уточнение будет предоставлено немного позже (сейчас я работаю)

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

Пример того, как его использовать:

Если Range(«A38:P38») пуст, будет напечатано True ; иначе это напечатало бы False .

Это вернет True если ни одна ячейка в Selection содержит каких-либо данных. Для определенного диапазона просто замените RANGE(. ) на Selection .

Источник

score:-1

Another solution to test for empty array

if UBound(ar) < LBound(ar) then msgbox "Your array is empty!"

Or, if you already know that LBound is 0

if -1 = UBound(ar) then msgbox "Your array is empty!"

This may be faster than join(). (And I didn’t check with negative indexes)

Here is my sample to filter 2 string arrays so they do not share same strings.

' Filtering ar2 out of strings that exists in ar1

For i = 0 To UBound(ar1)

    ' filter out any ar2.string that exists in ar1
    ar2 = Filter(ar2 , ar1(i), False)    

    If UBound(ar2) < LBound(ar2) Then
       MsgBox "All strings are the same.", vbExclamation, "Operation ignored":
       Exit Sub

    End If

Next

' At this point, we know that ar2 is not empty and it is filtered 
'

score:-1

Public Function arrayIsEmpty(arrayToCheck() As Variant) As Boolean
    On Error GoTo Err:
    Dim forCheck
    forCheck = arrayToCheck(0)
    arrayIsEmpty = False
    Exit Function
Err:
    arrayIsEmpty = True
End Function

score:0

I’ll generalize the problem and the Question as intended.
Test assingment on the array, and catch the eventual error

Function IsVarArrayEmpty(anArray as Variant)
Dim aVar as Variant

IsVarArrayEmpty=False
On error resume next
aVar=anArray(1)
If Err.number then '...still, it might not start at this index
    aVar=anArray(0)
    If Err.number then IsVarArrayEmpty=True ' neither 0 or 1 yields good assignment
EndIF
End Function

Sure it misses arrays with all negative indexes or all > 1… is that likely? in weirdland, yes.

score:0

Personally, I think one of the answers above can be modified to check if the array has contents:

if UBound(ar) > LBound(ar) Then

This handles negative number references and takes less time than some of the other options.

score:0

You can check if the array is empty by retrieving total elements count using JScript’s VBArray() object (works with arrays of variant type, single or multidimensional):

Sub Test()

    Dim a() As Variant
    Dim b As Variant
    Dim c As Long

    ' Uninitialized array of variant
    ' MsgBox UBound(a) ' gives 'Subscript out of range' error
    MsgBox GetElementsCount(a) ' 0

    ' Variant containing an empty array
    b = Array()
    MsgBox GetElementsCount(b) ' 0

    ' Any other types, eg Long or not Variant type arrays
    MsgBox GetElementsCount(c) ' -1

End Sub

Function GetElementsCount(aSample) As Long

    Static oHtmlfile As Object ' instantiate once

    If oHtmlfile Is Nothing Then
        Set oHtmlfile = CreateObject("htmlfile")
        oHtmlfile.parentWindow.execScript ("function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}"), "jscript"
    End If
    GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)

End Function

For me it takes about 0.3 mksec for each element + 15 msec initialization, so the array of 10M elements takes about 3 sec. The same functionality could be implemented via ScriptControl ActiveX (it is not available in 64-bit MS Office versions, so you can use workaround like this).

score:0

if Ubound(yourArray)>-1 then
 debug.print "The array is not empty"
else
 debug.print "EMPTY"
end if

score:0

You can check its count.

Here cid is an array.

if (jsonObject("result")("cid").Count) = 0 them
MsgBox "Empty Array"

I hope this helps.
Have a nice day!

score:1

Public Function IsEmptyArray(InputArray As Variant) As Boolean

   On Error GoTo ErrHandler:
   IsEmptyArray = Not (UBound(InputArray) >= 0)
   Exit Function

   ErrHandler:
   IsEmptyArray = True

End Function

score:1

You can use the below function to check if variant or string array is empty in vba

Function IsArrayAllocated(Arr As Variant) As Boolean
        On Error Resume Next
        IsArrayAllocated = IsArray(Arr) And _
                           Not IsError(LBound(Arr, 1)) And _
                           LBound(Arr, 1) <= UBound(Arr, 1)
End Function

Sample usage

Public Function test()
Dim Arr(1) As String
Arr(0) = "d"
Dim x As Boolean
x = IsArrayAllocated(Arr)
End Function

score:1

Another method would be to do it sooner. You can create a Boolean variable and set it to true once you load data to the array. so all you really need is a simple if statement of when you load data into the array.

score:1

Function IsVarArrayEmpty(anArray As Variant) as boolean
    On Error Resume Next
    IsVarArrayEmpty = true
    IsVarArrayEmpty = UBound(anArray) < LBound(anArray)
End Function

Maybe ubound crashes and it remains at true, and if ubound < lbound, it’s empty

score:1

To check whether a Byte array is empty, the simplest way is to use the VBA function StrPtr().

If the Byte array is empty, StrPtr() returns 0; otherwise, it returns a non-zero value (however, it’s not the address to the first element).

Dim ar() As Byte
Debug.Assert StrPtr(ar) = 0

ReDim ar(0 to 3) As Byte
Debug.Assert StrPtr(ar) <> 0

However, it only works with Byte array.

score:2

Simplified check for Empty Array:

Dim exampleArray() As Variant 'Any Type

If ((Not Not exampleArray) = 0) Then
      'Array is Empty
Else
      'Array is Not Empty
End If

score:2

Here is another way to do it. I have used it in some cases and it’s working.

Function IsArrayEmpty(arr As Variant) As Boolean

Dim index As Integer

index = -1
    On Error Resume Next
        index = UBound(arr)
    On Error GoTo 0

If (index = -1) Then IsArrayEmpty = True Else IsArrayEmpty = False

End Function

score:2

Based on ahuth’s answer;

Function AryLen(ary() As Variant, Optional idx_dim As Long = 1) As Long
    If (Not ary) = -1 Then
        AryLen = 0
    Else
        AryLen = UBound(ary, idx_dim) - LBound(ary, idx_dim) + 1
    End If
End Function

Check for an empty array; is_empty = AryLen(some_array)=0

score:3

Auth was closest but his answer throws a type mismatch error.

As for the other answers you should avoid using an error to test for a condition, if you can, because at the very least it complicates debugging (what if something else is causing that error).

Here’s a simple, complete solution:

option explicit
Function foo() As Variant

    Dim bar() As String

    If (Not Not bar) Then
        ReDim Preserve bar(0 To UBound(bar) + 1)
    Else
        ReDim Preserve bar(0 To 0)
    End If

    bar(UBound(bar)) = "it works!"

    foo = bar

End Function

score:4

This code doesn’t do what you expect:

If Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

If you pass an empty string ("") or vbNullString to Dir, it will return the name of the first file in the current directory path (the path returned by CurDir$). So, if SigString is empty, your If condition will evaluate to True because Dir will return a non-empty string (the name of the first file in the current directory), and GetBoiler will be called. And if SigString is empty, the call to fso.GetFile will fail.

You should either change your condition to check that SigString isn’t empty, or use the FileSystemObject.FileExists method instead of Dir for checking if the file exists. Dir is tricky to use precisely because it does things you might not expect it to do. Personally, I would use Scripting.FileSystemObject over Dir because there’s no funny business (FileExists returns True if the file exists, and, well, False if it doesn’t). What’s more, FileExists expresses the intent of your code much clearly than Dir.

Method 1: Check that SigString is non-empty first

If SigString <> "" And Dir(SigString) <> "" Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

Method 2: Use the FileSystemObject.FileExists method

Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")

If fso.FileExists(SigString) Then
    Signature = GetBoiler(SigString) 
Else
    Signature = "" 
End If

score:4

I am simply pasting below the code by the great Chip Pearson. It works a charm.
Here’s his page on array functions.

I hope this helps.

Public Function IsArrayEmpty(Arr As Variant) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' IsArrayEmpty
' This function tests whether the array is empty (unallocated). Returns TRUE or FALSE.
'
' The VBA IsArray function indicates whether a variable is an array, but it does not
' distinguish between allocated and unallocated arrays. It will return TRUE for both
' allocated and unallocated arrays. This function tests whether the array has actually
' been allocated.
'
' This function is really the reverse of IsArrayAllocated.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

    Dim LB As Long
    Dim UB As Long

    err.Clear
    On Error Resume Next
    If IsArray(Arr) = False Then
        ' we weren't passed an array, return True
        IsArrayEmpty = True
    End If

    ' Attempt to get the UBound of the array. If the array is
    ' unallocated, an error will occur.
    UB = UBound(Arr, 1)
    If (err.Number <> 0) Then
        IsArrayEmpty = True
    Else
        ''''''''''''''''''''''''''''''''''''''''''
        ' On rare occasion, under circumstances I
        ' cannot reliably replicate, Err.Number
        ' will be 0 for an unallocated, empty array.
        ' On these occasions, LBound is 0 and
        ' UBound is -1.
        ' To accommodate the weird behavior, test to
        ' see if LB > UB. If so, the array is not
        ' allocated.
        ''''''''''''''''''''''''''''''''''''''''''
        err.Clear
        LB = LBound(Arr)
        If LB > UB Then
            IsArrayEmpty = True
        Else
            IsArrayEmpty = False
        End If
    End If

End Function

score:5

When writing VBA there is this sentence in my head: «Could be so easy, but…»

Here is what I adopted it to:

Private Function IsArrayEmpty(arr As Variant)
  ' This function returns true if array is empty
  Dim l As Long

  On Error Resume Next
  l = Len(Join(arr))
  If l = 0 Then
    IsArrayEmpty = True
  Else
    IsArrayEmpty = False
  End If

  If Err.Number > 0 Then
      IsArrayEmpty = True
  End If

  On Error GoTo 0
End Function

Private Sub IsArrayEmptyTest()
  Dim a As Variant
  a = Array()
  Debug.Print "Array is Empty is " & IsArrayEmpty(a)
  If IsArrayEmpty(a) = False Then
    Debug.Print "  " & Join(a)
  End If
End Sub

score:7

I see similar answers on here… but not mine…

This is how I am unfortunatley going to deal with it… I like the len(join(arr)) > 0 approach, but it wouldn’t work if the array was an array of emptystrings…

Public Function arrayLength(arr As Variant) As Long
  On Error GoTo handler

  Dim lngLower As Long
  Dim lngUpper As Long

  lngLower = LBound(arr)
  lngUpper = UBound(arr)

  arrayLength = (lngUpper - lngLower) + 1
  Exit Function

handler:
  arrayLength = 0 'error occured.  must be zero length
End Function

score:29

If you test on an array function it’ll work for all bounds:

Function IsVarArrayEmpty(anArray As Variant)

Dim i As Integer

On Error Resume Next
    i = UBound(anArray,1)
If Err.number = 0 Then
    IsVarArrayEmpty = False
Else
    IsVarArrayEmpty = True
End If

End Function

score:78

As you are dealing with a string array, have you considered Join?

If Len(Join(FileNamesList)) > 0 Then

score:78

Go with a triple negative:

If (Not Not FileNamesList) <> 0 Then
    ' Array has been initialized, so you're good to go.
Else
    ' Array has NOT been initialized
End If

Or just:

If (Not FileNamesList) = -1 Then
    ' Array has NOT been initialized
Else
    ' Array has been initialized, so you're good to go.
End If

In VB, for whatever reason, Not myArray returns the SafeArray pointer. For uninitialized arrays, this returns -1. You can Not this to XOR it with -1, thus returning zero, if you prefer.

               (Not myArray)   (Not Not myArray)
Uninitialized       -1                 0
Initialized    -someBigNumber   someOtherBigNumber

Source

Related Query

  • How to check for empty array in vba macro
  • VBA for Excel — How to check intersection of ranges are not empty
  • How to check for an empty field read into a VBA date
  • Excel Macro Loop between 2 columns and check for empty cell and add cell VBA or C#
  • VBA / Excel Macro — How to Check a Cell for a Specific Formula
  • Check for empty array indexes in VBA (that can include objects)
  • How to store singe dim in array for loop through multiple work book using VBA Macro
  • How to check whether the first array entry is empty in VBA
  • How can you check for null in a VBA DAO record set?
  • How to initialize a multidimensional array variable in vba for excel
  • How to check from .net code whether «Trust access to the VBA project object model» is enabled or not for an Excel application?
  • vba — checking for empty array
  • How to check if Variant is empty and assign other variable to it in Excel VBA
  • How to return array() in vba function to use it in cells Array formulas (matricial formula) : for split texte in multi cells
  • Excel VBA — How to check for presence of a table in a different workbook?
  • How to check if an array is empty in VBA?
  • How to pass an empty optional argument from Python to Excel VBA macro
  • VBA How to check if an Array contains a string in a Range
  • How do I check for file encryption in VBA (MSAccess)
  • How to apply vlookup only for empty cells using vba and another workbook
  • ADODB Connection Timeout in VBA for Excel 2016 — how to check if a connection is still active?
  • How to Populate Multidimensional Array in Excel Macro using For Each Loop With Formula?
  • VBA check for empty cells in column and print value
  • How to define a custom date-time object in VBA for Macro programming
  • VBA Variant — IsNull and IsEmpty both false for empty array
  • How to check if a cell is empty using VBA
  • How to use Sum Function for an Array of Worksheets in VBA
  • VBA Excel how to activate macro for sheet 2, 3 and 4 from sheet 1
  • How to set some sort of array for VBA find/replace scripts
  • I created a VBA excel macro for finding duplicate values, how can I improve my code?

More Query from same tag

  • Loop through cells; Copy if not blank; Paste in sheet2 unformatted
  • How do I compare two columns for matching and non matching values and get it in the format that I want?
  • Open Print Dialog on Mac
  • How to check if two rows are identical and contain the same data in a list of rows
  • VBA GetPrivateProfileString
  • Worsksheet behaving as if it is grouped, when it isn’t
  • Macro to color Summary Tasks is 90% working, cannot figure out why it is not 100% working
  • Extract data from Summit FT
  • Copy-paste with loop, different ranges under each other
  • Formula to apply to delete blank cells and the cell next to it for multiple columns
  • Finding the last element of Object/ArrayList in Excel VBA
  • Powerpoint VBA dont close Excel
  • can an excel respond to an key press event when the excel itself is not active
  • Copy from a cell of a column to a specific cell
  • Set Toggle Button value on custom ribbon tab
  • VBA sheets.activate will not change the sheet it takes information from
  • Check existing sheet in each checking excel file
  • Pasting Values as Displayed
  • Trying to delete the first sheet in each excel file and then copying from each tab to the master workbook with the same tab names
  • Internet Explorer file download Excel file filename
  • My Audit Trail Script Isn’t Working
  • Loop Through Each Print Page in Worksheet with VBA
  • Deleting new duplicates but not the old ones
  • how to export all items in listbox to excel in vb
  • WordBasic MACRO for Word 365 runtime error ‘102’
  • Insert blank rows in excel if row above is not empty
  • Send email from draft folder
  • How can I retrieve JSON from an HTTP endpoint, from within Excel on MacOS, and parse it?
  • RTD.RefreshData crashes when invoked from modal form
  • Excel VBA script index error

Проверка переменных и выражений с помощью встроенных функций VBA Excel: IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject.

Проверка переменных и выражений

Встроенные функции VBA Excel — IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject — проверяют значения переменных и выражений на соответствие определенному типу данных или специальному значению.

Синтаксис функций для проверки переменных и выражений:

Expression — выражение, переменная или необязательный аргумент для IsMissing.

Все функции VBA Excel для проверки переменных и выражений являются логическими и возвращают значение типа Boolean — True или False.

Функция IsArray

Описание функции

Функция IsArray возвращает значение типа Boolean, указывающее, является ли переменная массивом:

  • True — переменная является массивом;
  • False — переменная не является массивом.

Пример с IsArray

Sub Primer1()

Dim arr1(), arr2(1 To 10), arr3

    Debug.Print IsArray(arr1)  ‘Результат: True

    Debug.Print IsArray(arr2)  ‘Результат: True

    Debug.Print IsArray(arr3)  ‘Результат: False

arr3 = Array(1, 2, 3, 4, 5)

    Debug.Print IsArray(arr3)  ‘Результат: True

End Sub

Как показывает пример, функция IsArray возвращает True и в том случае, если переменная только объявлена как массив, но еще не содержит значений.

Функция IsDate

Описание функции

Функция IsDate возвращает логическое значение, указывающее, содержит ли переменная значение, которое можно интерпретировать как дату:

  • True — переменная содержит дату, выражение возвращает дату, переменная объявлена с типом As Date;
  • False — в иных случаях.

Пример с IsDate

Sub Primer2()

Dim d1 As String, d2 As Date

    Debug.Print IsDate(d1)  ‘Результат: False

    Debug.Print IsDate(d2)  ‘Результат: True

d1 = «14.01.2023»

    Debug.Print IsDate(d1)  ‘Результат: True

    Debug.Print IsDate(Now)  ‘Результат: True

End Sub

Функция IsEmpty

Описание функции

Функция IsEmpty возвращает значение типа Boolean, указывающее, содержит ли переменная общего типа (As Variant) значение Empty:

  • True — переменная содержит значение Empty;
  • False — переменной присвоено значение, отличное от Empty.

Пример с IsEmpty

Sub Primer3()

Dim s As String, v As Variant

    Debug.Print IsEmpty(s)  ‘Результат: False

    Debug.Print IsEmpty(v)  ‘Результат: True

v = 125

    Debug.Print IsEmpty(v)  ‘Результат: False

Range(«A1»).Clear

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: True

Range(«A1») = 123

    Debug.Print IsEmpty(Range(«A1»))  ‘Результат: False

End Sub

Как видно из примера, функцию IsEmpty можно использовать для проверки ячеек на содержание значения Empty (пустая ячейка общего формата).

Функция IsError

Описание функции

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

  • True — аргумент функции является значением ошибки, определенной пользователем;
  • False — в иных случаях.

Пользователь может определить одну или несколько ошибок для своей процедуры или функции с рекомендациями действий по ее (их) исправлению. Возвращается номер ошибки с помощью функции CVErr.

Пример с IsError

Допустим, пользователь определил, что ошибка №25 означает несоответствие аргумента функции Vkuba числовому формату:

Function Vkuba(x)

    If IsNumeric(x) Then

        Vkuba = x ^ 3

    Else

        Vkuba = CVErr(25)

    End If

End Function

Sub Primer4()

    Debug.Print Vkuba(5)  ‘Результат: 125

    Debug.Print IsError(Vkuba(5))  ‘Результат: False

    Debug.Print Vkuba(«пять»)  ‘Результат: Error 25

    Debug.Print IsError(Vkuba(«пять»))  ‘Результат: True

End Sub

Функция IsMissing

Описание функции

Функция IsMissing возвращает значение типа Boolean, указывающее, был ли необязательный аргумент типа данных Variant передан процедуре:

  • True — если в процедуру не было передано значение для необязательного аргумента;
  • False — значение для необязательного аргумента было передано в процедуру.

Пример с IsMissing

Function Scepka(x, Optional y)

    If Not IsMissing(y) Then

        Scepka = x & y

    Else

        Scepka = x & » (а необязательный аргумент не подставлен)»

    End If

End Function

Sub Primer5()

    Debug.Print Scepka(«Тропинка», » в лесу»)  ‘Результат: Тропинка в лесу

    Debug.Print Scepka(«Тропинка»)  ‘Результат: Тропинка (а необязательный аргумент не подставлен)

End Sub

Функция IsNull

Описание функции

Функция IsNull возвращает логическое значение, указывающее, является ли Null значением переменной или выражения:

  • True — значением переменной или выражения является Null;
  • False — в иных случаях.

Пример с IsNull

Функция IsNull особенно необходима из-за того, что любое условие с выражением, в которое входит ключевое слово Null, возвращает значение False:

Sub Primer6()

Dim Var

Var = Null

    If Var = Null Then Debug.Print Var  ‘Результат: «»

    If Var <> Null Then Debug.Print Var  ‘Результат: «»

    If IsNull(Var) Then Debug.Print Var  ‘Результат: Null

End Sub

Функция IsNumeric

Описание функции

Функция IsNumeric возвращает значение типа Boolean, указывающее, можно ли значение выражения или переменной рассматривать как число:

  • True — если аргумент функции может рассматриваться как число;
  • False — в иных случаях.

Пример с IsNumeric

Sub Primer7()

Debug.Print IsNumeric(«3,14»)  ‘Результат: True

Debug.Print IsNumeric(«четыре»)  ‘Результат: False

End Sub

Функция IsObject

Описание функции

Функция IsObject возвращает логическое значение, указывающее, является ли переменная объектной:

  • True — переменная содержит ссылку на объект или значение Nothing;
  • False — в иных случаях.

Функция IsObject актуальна для переменных типа Variant, которые могут содержать как ссылки на объекты, так и значения других типов данных.

Пример с IsObject

Sub Primer8()

Dim myObj As Object, myVar As Variant

    Debug.Print IsObject(myObj)  ‘Результат: True

    Debug.Print IsObject(myVar)  ‘Результат: False

Set myVar = ActiveSheet

    Debug.Print IsObject(myVar)  ‘Результат: True

End Sub


Понравилась статья? Поделить с друзьями:
  • Excel vba if any value in range
  • Excel vba if any cell in range
  • Excel vba method open of object workbooks failed
  • Excel vba md5 файла
  • Excel vba max in array