Excel is empty string

When working with Excel formulas, a common term is «empty string». A text string is a text value like «apple». An empty string is a text value that has no value. Since text in Excel formulas must be enclosed in double quotes, an empty string appears as empty double quotes («»).

For example, in the screenshot shown, the formula D5, copied down, is:

=IF(C5>10,"x","")

Here, we use the IF function to check the value in column C5. If the value is greater than 10, the formula returns «x» as text. Otherwise, IF returns an empty string («»).

When an empty string is the result of a formula, it looks like the cell is blank. So, empty strings are commonly used to return a value that looks like nothing. In other words, return a result that appears as an empty cell.

One thing to note is that some functions will treat empty strings as if they do have a value. For example, the ISBLANK function will return FALSE if used on a cell that contains a formula that has returned «». Likewise, the COUNTA function will include cells that contain formulas that have returned «».

There are hundreds and hundreds of Excel sites out there. I’ve been to many and most are an exercise in frustration. Found yours today and wanted to let you know that it might be the simplest and easiest site that will get me where I want to go.

Get Training

Quick, clean, and to the point training

Learn Excel with high quality video training. Our videos are quick, clean, and to the point, so you can learn Excel in less time, and easily review key topics when needed. Each video comes with its own practice worksheet.

View Paid Training & Bundles

how do I check if the string variable is empty in vba?

if:

Dim StrFile1 As String, StrFile2 As String
Dim Text3 As String
Dim Len1 as Integer, Len2 As Integer 

  With NewMail
   Text3 = Cells(i, 3).Value
   StrPath = Cells(i, 2).Value & Text3
   Text = Cells(i, 1).Value

  .Subject = 
  ' adds the data in column3 with space as subject
  .From = 
  .To = Text
  .BCC = ""
  .TextBody = 

StrFile1 = Dir(StrPath & "*.txt")
   Len1 = Len(StrFile1)
   Do While Len(StrFile1) > 0
   .AddAttachment StrPath & StrFile1
   StrFile1 = Dir
   Loop

   StrFile2 = Dir(StrPath & "*.pdf")
   Len2 = Len(StrFile2)
   Do While Len(StrFile2) > 0
   .AddAttachment StrPath & StrFile2
   StrFile2 = Dir
   Loop

   If (Len1 & Len2) = 0 Then
   GoTo Last



  '.AddAttachment Text3
  .Send
End With
i = i + 1
Loop

Last:
End With
i = i + 1
Loop

Now i want to check simultaneously if Len1 and Len2 are 0, if so then I want to go to Last.

When I use this code I get a message/Compile error «Want to end with without with»
and
i am not sure if

If (Len1 & Len2) = 0 Then
       GoTo Last

this is a proper code.
and Do i need to declare the label Last??

asked Jun 6, 2016 at 17:14

Shank's user avatar

ShankShank

6533 gold badges9 silver badges21 bronze badges

4

You have many way to do that like below :

Dim StrFiles As String
StrFiles = Trim(StrFile1 & StrFile2)

If IsEmpty(StrFiles) Then
If StrFiles = vbNullString Then
If StrFiles = "" Then
If StrFiles = Empty Then
If Len(StrFiles) = 0 Then

you can use + operator to check 2 strings are empty reference to your code, because Len Function returns an integer containing either the number of characters in a string

If (Len1 + Len2) = 0 Then

answered Jun 6, 2016 at 17:28

Abdellah OUMGHAR's user avatar

Abdellah OUMGHARAbdellah OUMGHAR

3,6191 gold badge11 silver badges16 bronze badges

8

You can use Trim(strFile1 & vbNullString) = vbNullString to check if the string is empty.

So:

If Trim(strFile1 & vbNullString) = vbNullString Then
   Debug.print "Empty String!"
End If

Thanks to @LordPeter

Community's user avatar

answered Jun 6, 2016 at 17:20

BruceWayne's user avatar

BruceWayneBruceWayne

22.8k15 gold badges64 silver badges109 bronze badges

1

is.empty doesn’t exist for VBA, but the second option works.

Alternatively, you can write:

(strFile1 & strFile2) = vbNullString

or

(strFile1 & strFile2) = ""

answered Jun 6, 2016 at 17:20

basodre's user avatar

basodrebasodre

5,6801 gold badge14 silver badges22 bronze badges

Yet another way is:

If Len(strFile1 & strFile2) > 0 Then

I did test to ensure that strings which aren’t set return a length of 0, which appeared to be the case.

answered Jun 6, 2016 at 17:21

Soulfire's user avatar

SoulfireSoulfire

4,21821 silver badges32 bronze badges

1

If Blank | If Not Blank | Highlight Blank Cells

Use the IF function and an empty string in Excel to check if a cell is blank. Use IF and ISBLANK to produce the exact same result.

If Blank

Remember, the IF function in Excel checks whether a condition is met, and returns one value if true and another value if false.

1. The IF function below returns Yes if the input value is equal to an empty string (two double quotes with nothing in between), else it returns No.

Check If a Cell is Blank

Note: if the input cell contains a space, it looks blank. However, if this is the case, the input value is not equal to an empty string and the IF function above will return No.

2. Use IF and ISBLANK to produce the exact same result.

IsBlank Function in Excel

Note: the ISBLANK function returns TRUE if a cell is empty and FALSE if not. If the input cell contains a space or a formula that returns an empty string, it looks blank. However, if this is the case, the input cell is not empty and the formula above will return No.

If Not Blank

In Excel, <> means not equal to.

1. The IF function below multiplies the input value by 2 if the input value is not equal to an empty string (two double quotes with nothing in between), else it returns an empty string.

Check If a Cell is Not Blank

2. Use IF, NOT and ISBLANK to produce the exact same result.

Not and IsBlank Function in Excel

Highlight Blank Cells

You can use conditional formatting in Excel to highlight cells that are blank.

1. For example, select the range A1:H8.

Select Cells

2. On the Home tab, in the Styles group, click Conditional Formatting.

Click Conditional Formatting

3. Click Highlight Cells Rules, More Rules.

More Rules

4. Select Blanks from the drop-down list, select a formatting style and click OK.

Select Blanks

Result.

Highlight Blank Cells

Note: visit our page about conditional formatting to learn much more about this cool Excel feature.

Содержание

  1. ISBLANK Function
  2. Related functions
  3. Summary
  4. Purpose
  5. Return value
  6. Arguments
  7. Syntax
  8. Usage notes
  9. Examples
  10. Is not blank
  11. Empty string syntax
  12. Empty strings
  13. If cell is not blank
  14. Related functions
  15. Summary
  16. Generic formula
  17. Explanation
  18. IF function
  19. ISBLANK function
  20. LEN function
  21. Excel ISBLANK function to check if cell is empty or not
  22. Excel ISBLANK function
  23. ISBLANK in Excel — things to remember
  24. How to use ISBLANK in Excel
  25. Excel formula: if cell is blank then
  26. Excel formula: if cell is not blank then
  27. If cell is blank, then leave blank
  28. If any cell in range is blank, then do something
  29. If all cells in range are blank, then do something
  30. Excel formula: if cell is not blank, then sum
  31. If not blank then sum
  32. If blank then sum
  33. Sum if all cells in range are not blank
  34. Excel formula: count if cell is not blank
  35. Excel ISBLANK not working
  36. Treat zero-length strings as blanks
  37. Remove or ignore extra spaces

ISBLANK Function

Summary

The Excel ISBLANK function returns TRUE when a cell is empty, and FALSE when a cell is not empty. For example, if A1 contains «apple», ISBLANK(A1) returns FALSE.

Purpose

Return value

Arguments

Syntax

Usage notes

The ISBLANK function returns TRUE when a cell is empty, and FALSE when a cell is not empty. For example, if A1 contains «apple», ISBLANK(A1) returns FALSE. Use the ISBLANK function to test if a cell is empty or not. ISBLANK function takes one argument, value, which is a cell reference like A1.

The word «blank» is somewhat misleading in Excel, because a cell that contains only space will look blank but not be empty. In general, it is best to think of ISBLANK to mean «is empty» since it will return FALSE when a cell looks blank but is not empty.

Examples

If cell A1 contains nothing at all, the ISBLANK function will return TRUE:

If cell A1 contains any value, or any formula, the ISBLANK function will return FALSE:

Is not blank

To test if a cell is not blank, nest ISBLANK inside the NOT function like this:

The above formula will return TRUE when a cell is not empty, and FALSE when a cell is empty.

Empty string syntax

Many formulas will use an abbreviated syntax to test for empty cells, instead of the ISBLANK function. This syntax uses an empty string («») with Excel’s math operators «=» or «<>«. For example, to test if A1 is empty, you can use:

To test if A1 is not empty:

This syntax can be used interchangeably with ISBLANK. For example, inside the IF function:

is equivalent to:

Likewise, the formula:

Both will return result1 when A1 is not empty, and result2 when A1 is empty.

Empty strings

If a cell contains any formula, the ISBLANK function and the alternatives above will return FALSE, even if the formula returns an empty string («»). This can cause problems when the goal is to count or process blank cells that include empty strings.

One workaround is to use the LEN function to test for a length of zero. For example, the formula below will return TRUE if A1 is empty or contains a formula that returns an empty string:

So, inside the IF function, you can use LEN like this:

You can use this same approach to count cells that are not blank.

Источник

If cell is not blank

Summary

To test if a cell is not blank (i.e. has content), you can use a formula based on the IF function. In the example shown, the formula in cell E5 is:

As the formula is copied down it returns «Done» when a cell in column D is not blank and an empty string («») if the cell is blank.

Generic formula

Explanation

In this example, the goal is to create a formula that will return «Done» in column E when a cell in column D contains a value. In other words, if the cell in column D is «not blank», then the formula should return «Done». In the worksheet shown, column D is is used to record the date a task was completed. Therefore, if the column contains a date (i.e. is not blank), we can assume the task is complete. This problem can be solved with the IF function alone or with the IF function and the ISBLANK function. It can also be solved with the LEN function. All three approaches are explained below.

IF function

The IF function runs a logical test and returns one value for a TRUE result, and another value for a FALSE result. You can use IF to test for a blank cell like this:

In the first example, we test if A1 is empty with =»». In the second example, the <> symbol is a logical operator that means «not equal to», so the expression A1<>«» means A1 is «not empty». In the worksheet shown, we use the second idea in cell E5 like this:

If D5 is «not empty», the result is «Done». If D5 is empty, IF returns an empty string («») which displays as nothing. As the formula is copied down, it returns «Done» only when a cell in column D contains a value. To display both «Done» and «Not done», you can adjust the formula like this:

ISBLANK function

Another way to solve this problem is with the ISBLANK function. The ISBLANK function returns TRUE when a cell is empty and FALSE if not. To use ISBLANK directly, you can rewrite the formula like this:

Notice the TRUE and FALSE results have been swapped. The logic now is if cell D5 is blank. To maintain the original logic, you can nest ISBLANK inside the NOT function like this:

The NOT function simply reverses the result returned by ISBLANK.

LEN function

One problem with testing for blank cells in Excel is that ISBLANK(A1) or A1=»» will both return FALSE if A1 contains a formula that returns an empty string. In other words, if a formula returns an empty string in a cell, Excel interprets the cell as «not empty». To work around this problem, you can use the LEN function to test for characters in a cell like this:

This is a much more literal formula. We are not asking Excel if A1 is blank, we are literally counting the characters in A1. The LEN function will return a positive number only when a cell contains actual characters.

Источник

Excel ISBLANK function to check if cell is empty or not

by Svetlana Cheusheva, updated on March 14, 2023

The tutorial shows how to use ISBLANK and other functions to identify blank cells in Excel and take different actions depending on whether a cell is empty or not.

There are many situations when you need to check if a cell is empty or not. For instance, if cell is blank, then you might want to sum, count, copy a value from another cell, or do nothing. In these scenarios, ISBLANK is the right function to use, sometimes alone, but most often in combination with other Excel functions.

Excel ISBLANK function

The ISBLANK function in Excel checks whether a cell is blank or not. Like other IS functions, it always returns a Boolean value as the result: TRUE if a cell is empty and FALSE if a cell is not empty.

The syntax of ISBLANK assumes just one argument:

Where value is a reference to the cell you want to test.

For example, to find out if cell A2 is empty, use this formula:

To check if A2 is not empty, use ISBLANK together with the NOT function, which returns the reversed logical value, i.e. TRUE for non-blanks and FALSE for blanks.

Copy the formulas down to a few more cells and you will get this result:

ISBLANK in Excel — things to remember

The main point you should keep in mind is that the Excel ISBLANK function identifies truly empty cells, i.e. cells that contain absolutely nothing: no spaces, no tabs, no carriage returns, nothing that only appears blank in a view.

For a cell that looks blank, but in fact is not, an ISBLANK formula returns FALSE. This behavior occurs if a cell contains any of the following:

  • Formula that returns an empty string like IF(A1<>«», A1, «»).
  • Zero-length string imported from an external database or resulted from a copy/paste operation.
  • Spaces, apostrophes, non-breaking spaces ( ), linefeed or other non-printing characters.

How to use ISBLANK in Excel

To gain more understanding of what the ISBLANK function is capable of, let’s take a look at some practical examples.

Excel formula: if cell is blank then

Since Microsoft Excel does not have a built-in IFBLANK kind of function, you need to use IF and ISBLANK together to test a cell and perform an action if the cell is empty.

Here’s the generic version:

To see it in action, let’s check if a cell in column B (delivery date) has any value in it. If the cell is blank, then output «Open»; if the cell is not blank, then output «Completed».

=IF(ISBLANK(B2), «Open», «Completed»)

Please remember that the ISBLANK function only determines absolutely blank cells. If a cell contains something invisible to the human eye such as a zero-length string, ISBLANK would return FALSE. To illustrate this, please have a look at the screenshot below. The dates in column B are pulled from another sheet with this formula:

As the result, B4 and B6 contain empty strings («»). For these cells, our IF ISBLANK formula yields «Completed» because in terms of ISBLANK the cells are not empty.

If your classification of «blanks» includes cells containing a formula that results in an empty string, then use =»» for the logical test:

=IF(B2=»», «Open», «Completed»)

The screenshot below shows the difference:

Excel formula: if cell is not blank then

If you’ve closely followed the previous example and understood the formula’s logic, you should have no difficulties with modifying it for a specific case when an action shall only be taken when the cell is not empty.

Based on your definition of «blanks», choose one of the following approaches.

To identify only truly non-blank cells, reverse the logical value returned by ISBLANK by wrapping it into NOT:

Or use the already familiar IF ISBLANK formula (please notice that compared to the previous one, the value_if_true and value_if_false values are swapped):

To teat zero-length strings as blanks, use <>«» for the logical test of IF:

For our sample table, any of the below formulas will work a treat. They all will return «Completed» in column C if a cell in column B is not empty:

=IF(B2<>«», «Completed», «»)

If cell is blank, then leave blank

In certain scenarios, you may need a formula of this kind: If cell is blank do nothing, otherwise take some action. In fact, it’s nothing else but a variation of the generic IF ISBLANK formula discussed above, in which you supply an empty string («») for the value_if_true argument and the desired value/formula/expression for value_if_false.

For absolutely blank cells:

To regard empty strings as blanks:

In the table below, suppose you want to do the following:

  • If column B is empty, leave column C empty.
  • If column B contains a sales number, calculate the 10% commission.

To have it done, we multiply the amount in B2 by percentage and put the expression in the third argument of IF:

After copying the formula through column C, the result looks as follows:

If any cell in range is blank, then do something

In Microsoft Excel, there are a few different ways to check a range for empty cells. We will be using an IF statement to output one value if there is at least one empty cell in the range and another value if there are no empty cells at all. In the logical test, we calculate the total number of empty cells in the range, and then check if the count is greater than zero. This can be done with either COUNTBLANK or COUNTIF function:

Or a little bit more complex SUMPRODUCT formula:

For example, to assign the «Open» status to any project that has one or more blanks in columns B through D, you can use any of the below formulas:

=IF(SUMPRODUCT(—(B2:D2=»»))>0, «Open», «»)

Note. All these formulas treat empty strings as blanks.

If all cells in range are blank, then do something

To check if all cells in the range are empty, we will be using the same approach as in the above example. The difference is in the logical test of IF. This time, we count cells that are not empty. If the result is greater than zero (i.e. the logical test evaluates to TRUE), we know that not every cell in the range is blank. If the logical test is FALSE, that means all cells in the range are blank. So, we supply the desired value/expression/formula in the 3 rd argument of IF (value_if_false).

In this example, we will return «Not Started» for projects that have blanks for all the milestones in columns B through D.

The easiest way to count non-empty cells in Excel is by using the COUNTA function:

=IF(COUNTA(B2:D2)>0, «», «Not Started»)

Another way is COUNTIF for non-blanks («<>» as the criteria):

=IF(COUNTIF(B2:D2,»<>«)>0, «», «Not Started»)

Or the SUMPRODUCT function with the same logic:

=IF(SUMPRODUCT(—(B2:D2<>«»))>0, «», «Not Started»)

ISBLANK can also be used, but only as an array formula, which should be completed by pressing Ctrl + Shift + Enter , and in combination with the AND function. AND is needed for the logical test to evaluate to TRUE only when the result of ISBLANK for each cell is TRUE.

=IF(AND(ISBLANK(B2:D2)), «Not Started», «»)

Note. When choosing a formula for your worksheet, an important thing to consider is your understanding of «blanks». The formulas based on ISBLANK, COUNTA and COUNTIF with «<>» as the criteria look for absolutely empty cells. SUMPRODUCT also regards empty strings as blanks.

Excel formula: if cell is not blank, then sum

To sum certain cells when other cells are not blank, use the SUMIF function, which is especially designed for conditional sum.

In the table below, supposing you wish to find the total amount for the items that are already delivered and those that are not yet delivered.

If not blank then sum

To get the total of delivered items, check if the Delivery date in column B is not blank and if it isn’t, then sum the value in column C:

If blank then sum

To get the total of undelivered items, sum if the Delivery date in column B is blank:

=SUMIF(B2:B6, «», C2:C6)

Sum if all cells in range are not blank

To sum cells or perform some other calculation only when all cells in a given range are not blank, you can again use the IF function with the appropriate logical test.

For example, COUNTBLANK can bring us the total number of blanks in the range B2:B6. If the count is zero, we run the SUM formula; otherwise do nothing:

=IF(COUNTBLANK(B2:B6)=0, SUM(B2:B6), «»)

The same result can be achieved with an array IF ISBLANK SUM formula (please remember to press Ctrl + Shift + Enter to complete it correctly):

In this case, we use ISBLANK in combination with the OR function, so the logical test is TRUE if there is at least one blank cell in the range. Consequently, the SUM function goes to the value_if_false argument.

Excel formula: count if cell is not blank

As you probably know, Excel has a special function to count non-empty cells, the COUNTA function. Please be aware that the function counts cells containing any type of data, including the logical values of TRUE and FALSE, error, spaces, empty strings, etc.

For example, to count non-blank cells in the range B2:B6, this is the formula to use:

The same result can be achieved by using COUNTIF with the non-blank criteria («<>«):

To count blank cells, use the COUNTBLANK function:

=COUNTBLANK(B2:B6)

Excel ISBLANK not working

As already mentioned, ISBLANK in Excel returns TRUE only for really empty cells that contain absolutely nothing. For seemingly blank cells containing formulas that produce empty strings, spaces, apostrophes, non-printing characters, and the like, ISBLANK returns FALSE.

In a situation, when you want to treat visually empty cells as blanks, consider the following workarounds.

Treat zero-length strings as blanks

To consider cells with zero-length strings as blanks, in the logical test of IF, put either an empty string («») or the LEN function equal to zero.

=IF(A2=»», «blank», «not blank»)

=IF(LEN(A2)=0, «blank», «not blank»)

In case the ISBLANK function is malfunctioning because of blank spaces, the most obvious solution is to get rid of them. The following tutorial explains how to quickly remove leading, trailing and multiple in-between spaces, except for a single space character between words: How to remove extra spaces in Excel.

If for some reason removing excess spaces does not work for you, you can force Excel to ignore them.

To regard cells containing only space characters as empty, include LEN(TRIM(cell))=0 in the logical test of IF as an additional condition:

=IF(OR(A2=»», LEN(TRIM(A2))=0), «blank», «not blank»)

To ignore a specific non-printing character, find its code and supply it to the CHAR function.

For example, to identify cells containing empty strings and nonbreaking spaces ( ) as blanks, use the following formula, where 160 is the character code for a nonbreaking space:

=IF(OR(A2=»», A2=CHAR(160)), «blank», «not blank»)

That’s how to use the ISBLANK function to identify blank cells in Excel. I thank you for reading and hope to see you on our blog next week!

Источник

Skip to content

How to Use the ISBLANK function in Excel Step-by-Step

How to Use the ISBLANK function in Excel: Step-by-Step

What is ISBLANK?

Read it this way “Is it blank?”. More particularly, “Is this cell blank?”. The ISBLANK function is designed to answer the same question😊

You’d often see cells in Excel that’d appear blank but in essence, would not be blank.

The ISBLANK function can identify blank and non-blank cells in less than a second.

Join us through the article below to learn all about the ISBLANK function. Download our free sample workbook on your way down the article.

How to check if a cell is blank with ISBLANK

Like all the “IS___” functions, the ISBLANK function also returns a Boolean Value. The answer to the ISBLANK function returns TRUE if a cell is empty and FALSE if not.

How to apply the ISBLANK function in Excel? See below.

1. Here’s a list in Excel that has data on some cells. Whereas, the other cells appear blank.

Data in Excel

2. To see, how many of these cells are truly empty cells, write the ISBLANK function below.

= ISBLANK (A1)

Writing the ISBLANK function

We know this sounds super lame 😁 three cells are blank, and the rest are non-blank, anyone could see that.

3. But hit Enter and drag and drop the same formula to the whole list.

4. And the suspense comes to an end.

ISBLANK function find blank cells

5. The ISBLANK check is only true for one cell. Why not Cell A3 and A5?

Cell A3 has a space character.

A space character

And Cell A5 has an apostrophe.

An apostrophe

Both these characters are not visible in the cells but do have a sitting. So, the ISBLANK function identifies the cells containing any visible or invisible content.

ISBLANK formula example # 1: NOT and ISBLANK Function

Normally, the ISBLANK function would return TRUE if the cell is blank.

And return FALSE if the cell is not blank. 😉

What if you want the results to be the opposite? This means that you want to see if the cell is not blank.

1. Continuing with the same data list as above.

2. Write the ISBLANK function as below.

= ISBLANK (A1)

3. However, to swap the results, nest it into the NOT function as below.

= NOT(ISBLANK (A1))

Nesting the ISBLANK function into NOT

The NOT function applies a logical test to see if the cells are not blank. So, if the cells are not blank, it returns TRUE and vice versa.

The results are opposite to those above.

ISBLANK and Not Function

ISBLANK formula example # 2: IF and ISBLANK

The IF and ISBLANK function go very well together.

The IF function takes ISBLANK a step ahead and tells what to do next after you know if a cell is blank or not.

1. The list below shows the name of students with their roll numbers.

Students and their roll Numbers

Those who do not have a roll number allotted to their name, have been rejected.

Can we auto-fill this list with their admitted/rejected status?🤔

2. Write the ISBLANK function as below.

= ISBLANK (B2)

The above formula will give results as ‘True’ or ‘False’.

3. Nest it into the IF function as follows:

=IF ((ISBLANK (B2)), “Rejected”, “Admitted”) 

Writing the IF function

The first argument of the IF function is a logical test.

The second argument specifies that value to be returned if the test results are true. The third argument specifies the value to be returned if the test results are false.

The IF function returns the status

4. Cell B2 has a roll number. The ISBLANK test is false, and the IF function returns ‘Admitted’.

5. Drag and Drop the same to the whole list.

The IF function returns results for the whole list

Pro Tip!

There’s an abbreviated syntax to check if a cell is blank.

“<>” is also known as the empty string syntax. It includes double quotation marks with Excel operators.

To see if cell B1 is blank, write the formula = B1 = “”. If the answer is true, this means cell B1 is blank.

To see if cell B1 is not blank, write the formula = B1 “<>”. If the answer to this syntax is true, this means Cell B1 is not blank.

It is used in place of the ISBLANK function.

ISBLANK formula example # 3: SUMIF Function

The image below shows a list of grocery items.

Grocery List

For some grocery items, we have the batch number next to them. Whereas, the others don’t have any.

Can we sum only those items whose batch numbers are mentioned?

1. Write the SUMIF function as follows.

=SUMIF (B2:B6,

Cell reference B2:B6

The first argument defines the range for the criteria to be checked. We want the batch numbers, so the list of batch numbers (B2:B6) is referred to here.

2. Write the next argument as below.

=SUMIF (B2:B6, “<>”

Second argument of the worksheet function SUMIF

The sign “<>” defines non-blank cells. This means the range B2:B6 must be checked for non-blank cells. And only non-blank cells should be summed.

3. Define the range to be summed.

=SUMIF (B2:B6, “<>”, C2:C6)

Third argument of the SUM function

We have created a reference to cell C2:C6 as these cells contain the prices. And we want the prices to be summed.

4. Hit ‘Enter’ to see the formula applied.

Excel sums the prices of specified cell

Excel has summed the prices of some grocery items only.

It has only summed the prices of the grocery items for which a batch number is present. These include Cell C2, C3, and C6.

Double-check: Apply the SUM function to add these cells up or do some quick math.

20 + 15 + 50 = 85

That’s it – Now what?

When used in the right place, even a very simple function could turn out incredibly useful.

The ISBLANK function is one of those underrated functions of Excel that might seem useless alone. But when paired with other formulas, they will cut down your working time greatly.

This guide explains how to use the ISBLANK function and how to use it together with other excel functions. You might also use conditional formatting to highlight blank cells in Excel.

The ISBLANK and many more simple functions of Excel will be of use to you only if you master other major functions of Excel. Like the VLOOKUP, SUMIF, and IF functions.

My 30-minute free email course will help you master these and many other useful functions of Excel. Sign up now!

Other resources

The Microsoft Excel ISBLANK function would barely be of use individually. Most of the time you’d use it before applying another function in Excel.

Try reading our article on another similar topic like deleting blank rows in Excel.

Kasper Langmann2023-02-23T14:50:52+00:00

Page load link

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web More…Less

Windows: 2208 (Build 15601)
Mac: 16.65 (Build 220911)
Web: introduced 15-Sep-2022
iOS: 2.65 (Build 220905)
Android: 16.0.15629

Returns text that occurs before a given character or string. It is the opposite of the TEXTAFTER function.

Syntax

=TEXTBEFORE(text,delimiter,[instance_num], [match_mode], [match_end], [if_not_found])

The TEXTBEFORE function syntax has the following arguments:

text       The text you are searching within. Wildcard characters are not allowed. If text is an empty string, Excel returns empty text. Required.

delimiter       The text that marks the point before which you want to extract. Required.

instance_num       The instance of the delimiter after which you want to extract the text.   By default, instance_num = 1.  A negative number starts searching text from the end. Optional.

match_mode    Determines whether the text search is case-sensitive. The default is case-sensitive. Optional. Enter one of the following:

  • 0      Case sensitive.

  • 1      Case insensitive.


match_end
    Treats the end of text as a delimiter. By default, the text is an exact match. Optional. Enter the following:

  • 0      Don’t match the delimiter against the end of the text.

  • 1      Match the delimiter against the end of the text.

if_not_found    Value returned if no match is found. By default, #N/A is returned. Optional.

Remarks

When searching with an empty delimiter value, TEXTBEFORE matches immediately. It returns empty text when searching from the front (if instance_num is positive) and the entire text when searching from the end (if instance_num is negative).

Example

Result

=TEXTBEFORE(«Red riding hood’s, red hood», «hood»)

Red riding

=TEXTBEFORE(«Red riding hood’s, red hood», «»)

=TEXTBEFORE(«Red riding hood’s, red hood», «», -1)

Red riding hood’s, red hood

Errors

  • Excel returns a #VALUE! error if instance_num = 0 or if instance_num is greater than the length of text.

  • Excel returns a #N/A error if delimiter isn’t contained in text.

  • Excel returns a #N/A error if instance_num is greater than the number of occurrences of delimiter in text.

Examples

Copy the example data in each of the following tables and paste it in cell A1 of a new Excel worksheet. If you need to, you can adjust the column widths to see all the data.

Data

Little Red Riding Hood’s red hood

Little red Riding Hood’s red hood

Formulas

Results

=TEXTBEFORE(A2,»Red»)

Little 

=TEXTBEFORE(A3,»Red»)

#N/A

=TEXTBEFORE(A3,»red»,2)

Little red Riding Hood’s

=TEXTBEFORE(A3,»red»,-2)

Little

=TEXTBEFORE(A3,»Red»,,FALSE)

#N/A

=TEXTBEFORE(A3,»red»,3)

#N/A

Data

Marcus Aurelius

Socrates

Immanuel Kant

Formulas

Results

=TEXTBEFORE(A2,» «,,,1)

Marcus

=TEXTBEFORE(A3,» «,,,0)

#N/A

=TEXTBEFORE(A3,» «,,,1)

Socrates

=TEXTBEFORE(A4,» «,,,1)

Immanuel

See Also

Text functions (reference)

TEXTSPLIT function

TEXTAFTER function

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

Excel VBA — Empty, ZLS, Null, Nothing, Missing

————————————

Contents:

Empty

VarType Function

Null

Nothing

Missing

————————————

In excel vba we often refer to an Empty variable, ZLS (zero-length string) or null string or vbNullString, Null value, Missing Argument, or using the Nothing keyword with an object variable. It is important to differentiate and understand these terms and expressions while using them in your vba code. In this section, we will also understand using the VarType Function to determine the subtype of a variable, using the IsEmpty & IsNull Functions to check for Empty & Null values, and using the IsMissing Function to check whether optional arguments have been passed in the procedure or not.

Empty

When you declare a variable in your code using a Dim statement, you are setting aside sufficient memory for the variable (viz. 2 bytes for a Boolean or Integer variable, 4 bytes for a Long variable, and so on), and that the information being stored in the variable has an allowable range (of True or False  for a Boolean variable, a whole number between -32,768 to 32,767  for an Integer variable, a whole number between -2,147,483,648 to 2,147,483,647 for a variable subtype of Long, and so on). You will receive a run-time error if trying to assign a string value to a variable declared as Integer.

While declaring a variable if you do not specify its data type, or if you do not declare a variable at all it will default to Variant data type that can hold any type of data (string, date, time, Boolean, or numeric values) & can automatically convert the values that it contains. However, the disadvantage is that this makes Excel reserve more memory than is required (at least 16 bytes), and could also result in mistyping a variable name and not knowing it viz. you might type rowNumbre instead of rowNumber.

When you run a macro, all variables are initialized to a default value. The initial default value: for a numeric variable is zero; for a variable length string it is a zero-length or empty string («»); a fixed length string is initialized with the ASCII code 0, or Chr(0); an object variable defaults to Nothing; a Variant variable is initialized to Empty. In numeric context, an Empty variable denotes a zero while in a string context an Empty variable is a zero-length string («») . A zero-length string («») is also referred to as a null string. However, it is advised to explicitly specify an initial value for a variable instead of relying on its default initial value.

Empty indicates that no beginning value has been assigned to a Variant variable ie. a variable which has not been initialized. An Empty variable is represented as 0 in a numeric context or a zero-length string («») in a string context. Empty is not the same as Null which indicates that a variable contains no valid data.

The Empty keyword indicates an uninitialized variable value. It is used as a Variant subtype. You can assign the Empty keyword to explicitly set a variable to Empty.

IsEmpty Function

Use the IsEmpty Function to check whether a variable has been initialized. The function returns a Boolean value — returns True for an uninitialized variable or if a variable is explicitly set to Empty, otherwise the function returns False. Syntax: IsEmpty(expression), where expression is a Variant variable which you want to check. See below example(s) where we use this function to check if a variant variable is empty.

Empty, Blank, ZLS (zero-length string), null string & vbNullString

ZLS means a zero-length string («»), is also referred to as a null string, and has a length of zero (0). For all practical purposes using vbNullString is equivalent to a zero-length string («») because VBA interprets both in a similar manner, though both are actually not the same — a ‘zero length string’ actually means creating a string with no characters, whereas  vbNullString is a constant used for a null pointer meaning that no string is created and is also more efficient or faster to execute than ZLS. You can use «» or vbNullString alternatively in your code and both behave similarly. Note that there is no Blank keyword in vba, but we can refer to ‘blank cells‘ or «empty cells» in Excel spreadsheet. There are Excel worksheet functions for empty cells: (i) the COUNTA function counts the number of cells that are not empty, and also counts or includes a cell with empty text («») — also referrred to as empty string or zero length string — which is not counted as an empty cell; and (ii) the ISBLANK function returns True for an empty cell, and does not treat a zero-length string («») as a blank (empty cell) similarly as in COUNTA. Both the worksheet functions of ISBLANK and COUNTA distinguish between an empty cell and a cell containing a zero-length string (ie. «» as formula result).

VarType Function

Use the VarType Function to determine the subtype of a variable. Syntax: VarType(variable_name). The function returns an Integer indicating the variable’s subtype. The variable_name can be any variable except a user-defined data type (data type defined using the Type statement) variable. Examples of return values are: value 0 (VarType constant — vbEmpty, uninitialized / default), value 1 (VarType constant — vbNull, contains no valid data), value 2 (VarType constant — vbInteger, Integer), value 3 (VarType constant — vbLong, Long Integer), and so on. The VarType constants can be used anywhere in your code in place of the actual values.

Example — Empty variable:

Sub EmptyVar()
‘Empty variable

‘variable var1 has not been declared, hence it is a Variant data type:

‘returns 0, indicating variable subtype Empty:

MsgBox VarType(var1)

‘returns True, indicating variable subtype Empty:

MsgBox IsEmpty(var1)

‘returns False — is an Empty variable, not a Null variable — no beginning value has been assigned to a Variant variable:

MsgBox IsNull(var1)

‘Empty indicates a Variant variable for which you do not explicity specify an initial value, which by default gets initialized in VBA to a value that is represented as both a zero and a zero-length string.

‘returns both messages as below:

If var1 = 0 Then

MsgBox «Empty Variable represented as Zero»

End If

If var1 = «» Then

MsgBox «Empty Variable represented as a Zero-Length (Null) String»

End If

End Sub

Example — Testing for Empty:

Sub EmptyCheck()
‘testing for Empty

Dim var1 As Variant

‘variable not initialized — returns 0, indicating variable subtype Empty:

MsgBox VarType(var1)

‘returns True, indicating variable subtype Empty:

MsgBox IsEmpty(var1)

‘————

‘initialize the variable by specifying a string value:

var1 = «Hello»

‘returns 8, indicating variable subtype String:

MsgBox VarType(var1)

‘returns False, indicating variable is not Empty:

MsgBox IsEmpty(var1)

‘————

‘assign Empty keyword to set variable to Empty:

var1 = Empty

‘returns 0, indicating variable subtype Empty:

MsgBox VarType(var1)

‘returns True, indicating variable is Empty:

MsgBox IsEmpty(var1)

‘————

‘returns True for an empty worksheet cell, otherwise False:

MsgBox IsEmpty(ActiveCell)

End Sub

Example — Initialize a Variant variable:

Sub VarInitialized()
‘initialized variable

Dim var1 As Variant

‘variable has been initialized to a zero-length string («»):

var1 = «»

‘returns False, indicating variable is NOT Empty:

MsgBox IsEmpty(var1)

‘returns 8, indicating variable subtype String:

MsgBox VarType(var1)

‘returns — «Variable value is a Zero-Length String»

If var1 = «» Then

MsgBox «Variable value is a Zero-Length String»

Else

MsgBox «Variable value is NOT a Zero-Length String»

End If

‘returns — «Variable value is NOT Zero»

If var1 = 0 Then

MsgBox «Variable value is Zero»

Else

MsgBox «Variable value is NOT Zero»

End If

End Sub

Example — Check a zero-length string:

Sub CheckZLS()
‘check a zero-length string

Dim var1 As Variant

‘variable not initialized — returns 0, indicating variable subtype Empty — represented both as Zero (0) and a Zero-Length (Null) String:

MsgBox VarType(var1)

‘returns «True» for all If statements below:

If var1 = «» Then

MsgBox «True»

End If

If var1 = vbNullString Then

MsgBox «True»

End If

If Len(var1) = 0 Then

MsgBox «True»

End If

End Sub

Null

In VBA, Null keyword is used to indicate that a variable contains no valid data. A value indicating that a variable contains no valid data. Null is the result — (i) if you explicitly assign Null to a variable, or (ii) if you perform any operation between expressions that contain Null. The Null keyword is used as a Variant subtype ie. only a Variant variable can be Null, and and variable of any other subtype will give an error. Null is not the same as a zero-length string («»), and neither is Null the same as Empty, which indicates that a variable has not yet been initialized.

If you try to get the value of a Null variable or an expression that is Null, you will get an  error of ‘Invalid use of Null’ (Run-time Error 94). You will need to ensure the variable contains a valid value. Refer Image 1.

IsNull Function

The IsNull Function returns a Boolean value — True for an expression that is Null (containing no valid data), or else False for an expression that contains valid data. Syntax: IsNull(expression). The expression argument is a variant that contains a numeric or string value, and is necessary to specify.

Example — Integer variable:

Sub VarInteger()
‘no beginning value assigned to a variable of subtype Integer

Dim intVar As Integer

‘returns False (intVar is not Null & neither is it Empty) — no beginning value has been assigned to a variable of subtype Integer:

MsgBox IsNull(intVar)

‘returns 2, indicating variable subtype Integer:

MsgBox VarType(intVar)

‘returns — «Variable value is Zero» (The initial default value for a numeric variable is zero)

If intVar = 0 Then

MsgBox «Variable value is Zero»

Else

MsgBox «Variable value is NOT Zero»

End If

End Sub

Example — Evaluate Empty / Null variable, use IsNull & VarType vba functions:

Sub EmptyNullVar()
‘evaluate Empty / Null variable, use IsNull & VarType vba functions.

Dim var1 As Variant

‘returns False, var1 is not Null but an Empty variable (no beginning value has been assigned to a Variant variable):

MsgBox IsNull(var1)

‘variable not initialized — returns 0, indicating variable subtype Empty:

MsgBox VarType(var1)

‘returns the message because var1 is an Empty variable:

If var1 = 0 And var1 = vbNullString Then

MsgBox «Empty Variable represented both as Zero (0) and a Zero-Length (Null) String»

End If

‘——————-

‘variable is initialized to a zero-length string («») or vbNullString:

var1 = vbNullString

‘returns False — var1 is not a Null variable:

MsgBox IsNull(var1)

‘returns 8, indicating variable subtype String:

MsgBox VarType(var1)

‘——————-

‘explicitly assigning Null to a variable:

var1 = Null

‘returns True, for a Null variable, containing no valid data:

MsgBox IsNull(var1)

‘returns 1, indicating variable subtype Null:

MsgBox VarType(var1)

‘——————-

‘explicitly assigning valid data to a variable:

var1 = 12

‘returns False, for a variable containing valid data:

MsgBox IsNull(var1)

‘returns 2, indicating variable subtype Integer:

MsgBox VarType(var1)

‘——————-

‘returns False, for an expression containing valid data:

MsgBox IsNull(«Hello»)

End Sub

Example — Check a Null variable:

Sub CheckNull()
‘check a Null variable

‘explicitly assigning Null to a variable:

var1 = Null

‘returns 1, indicating variable subtype Null:

MsgBox VarType(var1)

‘returns the message, indicating variable subtype Null:

If VarType(var1) = vbNull Then

MsgBox «Null variable»

End If

‘an expression containing Null also evaluates to Null:

var2 = Null + 2

‘returns 1, indicating variable subtype Null:

MsgBox VarType(var2)

End Sub

Example — Check worksheet cell for Empty, ZLS, Null:

Sub WorksheetCell_ZLS_Empty_Null()
‘check worksheet cell for Empty, ZLS, Null

Dim var1 As Variant

‘returns True:

MsgBox vbNullString = «»

‘In the case where ActiveCell is Blank:

‘returns True for a Blank cell:

MsgBox ActiveCell.Value = «»

MsgBox ActiveCell.Value = vbNullString

MsgBox ActiveCell.Value = 0

MsgBox IsEmpty(ActiveCell.Value)

‘assign Active Cell value to variable:

var1 = ActiveCell.Value

‘returns True:

MsgBox IsEmpty(var1)

MsgBox var1 = vbNullString

MsgBox var1 = «»

MsgBox var1 = 0

‘returns False:

MsgBox VarType(var1) = vbNull

‘returns 0, indicating variable subtype Empty:

MsgBox VarType(var1)

‘If you enter «» in the Active Cell ie. the active cell contains the value: =«»
‘returns True:

MsgBox ActiveCell.Value = «»

MsgBox ActiveCell.Value = vbNullString

‘returns False:

MsgBox ActiveCell.Value = 0

MsgBox IsEmpty(ActiveCell.Value)

End Sub

Nothing

Assigning the Nothing keyword to an object variable disassociates the variable from an actual object. Nothing is assigned to an object variable by using the Set statement. You can assign the same actual object to multiple object variables in vba code, and this association uses your system resources and memory. The system resources and memory get released only either after you assign Nothing to all object variables using the Set statement which disassociates these variables from the actual object, or when all object variables go out of scope and get destroyed. It is advisable to explicity set all object variables to Nothing at the end of your procedure or even earlier while running your code when you finish using them, and this will release memory allocated to these variables.

Determine if the object variable is initialized — use Is Nothing for objects: To check if an object has been assigned or set, use the Is keyword with Nothing, viz. If object_variable Is Nothing. For objects, you cannot test if an object_variable is equal to something, and using = instead of Is will give an error.

Example — Using the Nothing keyword with an object variable:

Sub ObjNothing()
‘using the Nothing keyword with an object variable

Dim objVar As Object

‘returns True, because you have not yet assigned an actual object to the object variable:

MsgBox objVar Is Nothing

Set objVar = ActiveSheet

‘returns False, because you have assigned an actual object (Sheet) to the object variable:

MsgBox objVar Is Nothing

Set objVar = Nothing

‘returns «Variable not associated with an actual object», because you have disassociated the object variable from an actual object:

If objVar Is Nothing Then

MsgBox «Variable not associated with an actual object»

Else

MsgBox «Actual object is assigned to an Object variable»

End If

End Sub

Missing

Passing Arguments to Procedures: When an external value is to be used by a procedure to perform an action, it is passed to the procedure by variables. These variables which are passed to a procedure are called arguments. An argument is the value supplied by the calling code to a procedure when it is called. When the set of parentheses, after the procedure name in the Sub or Function declaration statement, is empty, it is a case when the procedure does not receive arguments. However, when arguments are passed to a procedure from other procedures, then these are listed or declared between the parentheses.

Optional Arguments: Arguments can be specified as Optional by using the Optional keyword before the argument to its left. When you specify an argument as Optional, all other arguments following that argument to its right must

also be specified as Optional. Note that specifying the Optional keyword makes an argument optional otherwise the argument will be required.

Check if an argument is Missing, using the IsMissing function: The Optional argument should be (though not necessary) declared as Variant data type to enable use of the IsMissing function which works only when used with variables declared as Variant data type. The IsMissing function is used to determine whether the optional argument was passed in the procedure or not and then you can adjust your code accordingly without returning an error. If the Optional argument is not declared as Variant in which case the IsMissing function will not work, the Optional argument will be assigned the default value for its data type which is 0 for numeric data type variables (viz. Integer, Double, etc) and Nothing (a null reference) for String or Object data type variables.

IsMissing function: The IsMissing function is used to check whether optional Variant arguments have been passed in the procedure or not. Syntax: IsMissing(argname). The function returns a Boolean value — True if no value is passed for the optional argument, and False if a value has been passed for the optional argument. If the IsMissing function returns True for an argument, using the missing argument in the code will cause an error, and thus using this function will help in adjusting your code accordingly.

Example of using the IsMissing function to check if an argument is Missing:

Function FullName(strFirstName As String, Optional strSecondName As Variant) As String
‘The declaration of the procedure contains two arguments, the second argument is specified as Optional. Declaring the Optional argument as Variant data type will enable use of the IsMissing function.

‘The IsMissing function is used to determine whether the optional argument was passed in the procedure, and if not, you can adjust your code accordingly without returning an error.

If IsMissing(strSecondName) Then

FullName = strFirstName

Else

FullName = strFirstName & » « & strSecondName

End If

End Function

Sub GetName()

Dim strGivenName As String

strGivenName = InputBox(«Enter Given Name»)

‘specifying only the first argument & omitting the second argument which is optional:

MsgBox FullName(strGivenName)

End Sub

Cover image for VBA How-To: If/Else and Checking For Empty Strings

*Note:* This post was originally posted on my blog. I hope posting it here will help reach those whom it will help.

Recently I have been using VBA for a project in Excel and, though I know what I want to express in VBA, I don’t always know the syntax since it isn’t my main programming language. I had to look up the syntax for the if / else conditional clause and how to check whether a string variable is empty. Given that I’m an experienced software engineer and still had to look them up I thought sharing them with you here would be helpful.

Note: Don’t just copy and paste before reading the article. Copying and pasting without understanding is unwise. You do so at your own danger.

If – Then – Else Conditional Statements In VBA

The if – else conditional statement is a staple of any programming language. In each language they have the same meaning. That is if some condition is true then take some action. Otherwise do something else or skip the action. Each language, however, has a slightly different way of saying this; that is each language has a different syntax.

In the case of VBA this is handled as follows (and as described in this guide on Microsoft’s docs website. The documentation is here):

If [condition] Then
    ' code
ElseIf [condition] Then
    ' code
Else
    ' code
End If

Checking String Variables For Emptiness

There are two common checks needed when dealing with data coming from a source outside the control of code you’re writing. These are:

  • Did I get data or is it empty?
  • Does the data conform to what I expect and can deal with?

In the case of the code I was writing I’ve got a class with member variables some of which are optional. When I am going to use them to pass the data on I need to know if there is data present to decide what to do with them. The last piece of pertinent information is that I am treating all the variables as strings because I will be sending the data over an API.

Can We Use The IsEmpty() function?

My initial search for how to check whether a string is empty led me to the IsEmpty() function. This seems like a really good fit for what I was looking for. As described in the documentation:

Returns a Boolean value indicating whether a variable has been initialized.

Given that I want to check whether a member variable of my class has been initialized to a value this looks like exactly what I want. As I was about to write this, however, I thought it would be a good idea to test this just to make sure that I am giving you correct information. As such, I wrote this small bit of code:

Sub CheckVarForEmpty()
    Dim stringVar As String
    If IsEmpty(stringVar) = True Then
        MsgBox "Variable Is Empty!"
    End If
End Sub

After writing this I ran this fully expecting to have a message box pop up saying that the variable is empty. However it did NOT pop up.

VBA Debugger To The Rescue!

However, when I debugged the code to make sure that the message box was really being skipped, I noticed that the variable showed that it had the value “”. Now, to me, this looks like an empty string but I decided to write another conditional testing the value of the string against “”:

Sub CheckVarForEmpty()
    Dim stringVar As String
    If stringVar = "" Then
        MsgBox "Varable Is = to Empty String"
    End If
End Sub

Sure enough the message box is shown. Hooray! This means that checking a string against “” successfully determines if a string variable is empty.

Why Didn’t IsEmpty() Work?

However, because I was curious I why IsEmpty() did not return true in my first attempt, I went back to the documentation and read it again. It specifically says that IsEmpty() only returns True if a variable is not initialized or explicitly set to Empty. If you notice in my first example I declare stringVar as a string because I am used to programming in strongly typed languages and it makes sense to me to mark how a variable is to be used. Given that the documentation for IsEmpty() shows examples where the variables were NOT declared with types. This made me wonder if, by declaring a variable with a type, it initializes it to a value (“” in the case of strings). This would make IsEmpty() return False. As such I wrote another test to see if this train of thought is valid:

Sub CheckVarForEmpty()
    Dim myVar
    If IsEmpty(myVar) = True Then
        MsgBox "MyVar is Empty!"
    End If
End Sub

Sure enough the message box in this test popped up as the documentation indicated it would. This, for me, confirms that declaring a variable in VBA as a particular type will initialize it in a manner appropriate for that type.

Conclusion — I always have more to learn

This exercise shows that, despite my years of experience, there are always more things to learn. I hope that this helps you in your adventures in VBA. For me, the next things I will teach myself regarding VBA is more about how classes are constructed and destructed. I hope to bring you more knowledge as I gain it for myself.

Проверка переменных и выражений с помощью встроенных функций 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


Like this post? Please share to your friends:
  • Excel is date between two dates
  • Excel interop открыть файл
  • Excel interop not closing
  • Excel interop get range
  • Excel interop create file