Excel VBA Not
VBA Not is a logical function. NOT is one of the logical functions among others such as VBA IF, VBA OR and VBA AND. All these functions work in the same logical concept but all have different applications. Where VBA Not works mainly on Boolean. Which means we will get the output in the form of TRUE and FALSE. And VBA Not is the opposite of the input we feed. Suppose, we want to compare 2 parameters such as temperature. The temperature of places A and B are 30˚C and we use VBA Not to compare the answer then we will definitely get FALSE, as VBA Not means No or No Equal. Opposite to this, if the temperature of place A is 30˚C and temperature of the place B is 35˚C then using VBA Not here will give us the answer as TRUE as both the values are not equal.
How to Use Not Function in Excel VBA?
Below are the different examples to use Not function in Excel VBA.
You can download this VBA Not Excel Template here – VBA Not Excel Template
Example #1
In this example, we will compare 2 numbers and see what type of output we would get. To execute this, follow the below steps:
Step 1: Open a Module from the Insert menu tab as shown below.
Step 2: Now write the subprocedure in the name of VBA Not or in any other name as per your choice as shown below.
Code:
Sub VBA_Not() End Sub
Step 3: For numbers, we used to use Integer but as here we will be using NOT with numbers, so we will use String data type.
Code:
Sub VBA_Not() Dim A As String End Sub
Step 4: Select the numbers which we want to compare. Here we will be comparing 10 and 20 and see if Number 20 is greater than 10 or not using Not function as shown below.
Code:
Sub VBA_Not() Dim A As String A = Not (10 < 20) End Sub
Step 5: Now to print the output, we will use the message box as shown below.
Code:
Sub VBA_Not() Dim A As String A = Not (10 < 20) MsgBox A End Sub
Step 6: Run the code by pressing the F5 key or by clicking on the Play button. We will get the message as FALSE.
We all know that number 20 is greater than 10. But VBA Not is the logical function that always gives the negative answer or opposite answer from the value we feed. So, as per VBA Not, number 20 is NOT greater than 10.
Example #2
There is another way to implement VBA Not. This time we will use If-End If loop to execute VBA Not. For this, follow the below steps:
Step 1: Write the subprocedure of VBA Not as shown below.
Code:
Sub VBA_Not2() End Sub
Step 2: Again we will use the variable as String here as well.
Code:
Sub VBA_Not2() Dim A As String End Sub
Step 3: Here we will compare whether 2 numbers are equal or not. Let’s compare number 10 with 10 and see what type of answer we will get. For this, open If loop and in condition write if NOT 10 is equal to 10 as shown below.
Code:
Sub VBA_Not2() Dim A As String If Not (10 = 10) Then End Sub
Step 4: If the above condition is satisfied then we will get the answer as TRUE.
Code:
Sub VBA_Not2() Dim A As String If Not (10 = 10) Then A = "TRUE" End Sub
Step 5: Else give us the answer as FALSE. After that close the loop by End-If.
Code:
Sub VBA_Not2() Dim A As String If Not (10 = 10) Then A = "TRUE" Else A = "FALSE" End If End Sub
Step 6: To see the output, we will use a message box with variable A.
Code:
Sub VBA_Not2() Dim A As String If Not (10 = 10) Then A = "TRUE" Else A = "FALSE" End If MsgBox A End Sub
Step 7: Run the code by pressing the F5 key or by clicking on the Play button. We will get the output message as FALSE.
Which means although number 10 is equal to 10 but since we used NOT so we are getting the opposite answer here.
Example #3
VBA Not can be used to compare the marks as well. Below we have 2 subjects rows under that a student got 61 in Subject1 and 2 in Subject2. And we will get the result in cell B3.
Follow the below steps:
Step 1: Write the subprocedure of VBA Not as shown below.
Code:
Sub VBA_Not3() End Sub
Step 2: Define 2 variable for Subject1 and Subject2 using Integer and one of result using String data type as shown below.
Code:
Sub VBA_Not3() Dim Subject1 As Integer Dim Subject2 As Integer Dim result As String End Sub
Step 3: Now select the range cell which has the number for respective subjects as shown below.
Code:
Sub VBA_Not3() Dim Subject1 As Integer Dim Subject2 As Integer Dim result As String Subject1 = Range("B1").Value Subject2 = Range("B2").Value End Sub
Step 4: Now use If loop with VBA Not as marks in Subject1 is greater than equal to 70 and for subject2 is greater than 30 in If condition, then result is “Pass”.
Code:
Sub VBA_Not3() Dim Subject1 As Integer Dim Subject2 As Integer Dim result As String Subject1 = Range("B1").Value Subject2 = Range("B2").Value If Not (Subject1 >= 70 And Subject2 > 30) Then result = "Pass" End Sub
Step 5: Else the student is Fail.
Code:
Sub VBA_Not3() Dim Subject1 As Integer Dim Subject2 As Integer Dim result As String Subject1 = Range("B1").Value Subject2 = Range("B2").Value If Not (Subject1 >= 70 And Subject2 > 30) Then result = "Pass" Else result = "Fail" End If End Sub
Step 6: At last, we will select cell B3 to get the result.
Code:
Sub VBA_Not3() Dim Subject1 As Integer Dim Subject2 As Integer Dim result As String Subject1 = Range("B1").Value Subject2 = Range("B2").Value If Not (Subject1 >= 70 And Subject2 > 30) Then result = "Pass" Else result = "Fail" End If Range("B3").Value = result End Sub
Step 7: Run the code by pressing the F5 key or by clicking on the Play button. We will get the result as PASS.
This means technically student is failed but we have used VBA Not in if the condition so the result is shown as Pass.
Pros of Excel VBA Not
- It is rarely used but when we need the opposite or negative answer then we can use it here.
- It is useful in comparing the negative outputs which may lead to giving a positive result.
Things to Remember
- VBA Not gives the opposite answer to the value we feed. It can be positive or negative, but the answer will be the opposite of that value we give as input.
- Always use VBA Not where we need to change the output opposite to the actual output.
- Remember to save the file as macro enable excel format so that this will retain the code for future use as well.
- Using VBA Not with If-Else loop will be more advisable.
Recommended Articles
This is a guide to VBA Not. Here we discuss how to use Not Function in Excel VBA along with practical examples and downloadable excel template. You may also look at the following articles to learn more –
- VBA IF Not
- VBA Variable Types
- VBA ScreenUpdating
- VBA Web Scraping
Logical functions are useful for calculations that require multiple conditions or criteria to test. In our earlier articles, we have seen “VBA IF,” “VBA OROr is a logical function in programming languages, and we have an OR function in VBA. The result given by this function is either true or false. It is used for two or many conditions together and provides true result when either of the conditions is returned true.read more,” and “VBA ANDVBA AND is an inbuilt logical function and a logical operator. Only when all of the conditions specified in this function are met , it returns the output as true. In contrast, if any of the conditions fails, the output is false.read more” conditions. This article will discuss the VBA NOT with the IF function in excelIF function in Excel evaluates whether a given condition is met and returns a value depending on whether the result is “true” or “false”. It is a conditional function of Excel, which returns the result based on the fulfillment or non-fulfillment of the given criteria.
read more. But, first, we need to look at the VBA NOT function to understand it.
Table of contents
- Excel VBA Not Function
- Examples
- Example #1
- Example #2 – NOT with IF Function
- Example #3 – Advanced NOT
- Recommended Articles
- Examples
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Not Function (wallstreetmojo.com)
Examples
You can download this VBA Not Excel Template here – VBA Not Excel Template
Example #1
The NOT function is available with VBA too. It works the same as the Excel function. For example, look at the below set of VBA codesVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.
Code:
Sub NOT_Example1() Dim k As String k = Not (45 = 45) MsgBox k End Sub
We have declared the variable “k” as a string in the above code.
Dim k As String
Next, we have assigned the value through the NOT functionNOT Excel function is a logical function in Excel that is also known as a negation function and it negates the value returned by a function or the value returned by another logical function.read more. Does it NOT function to say whether the number 45 equals 45 or not?
k = Not (45 = 45)
Next, we have assigned the value returned by the NOT function to the variable “k” in the message box.
MsgBox k
Run the code and see what the result is.
Example #2 – NOT with IF Function
As we said in one of the earlier articles, “IF with other logical functions are the best pairs in Excel.”
Similarly, NOT with IF is useful in many ways. For example, with IF, we can have our results instead of the default results of TRUE or FALSE.
Take the same example code above. Again, we will apply NOT with the IF function.
Code:
Sub NOT_Example2() Dim k As String If Not (45 = 45) Then k = "Test result is TRUE" Else k = "Test result is FALSE" End If MsgBox k End Sub
In the above code, we have altered the default results from “Test result is FALSE” and “Test result is TRUE.” If the supplied logical test is true, it will return “Test result is FALSE,” and if the supplied logical test is false, it will return. “Test result is TRUE.”
In the above code, we have a value of 45 = 45, so we will get the answer as follows.
Example #3 – Advanced NOT
The NOT function is utilized best with the IF function. For example, we can use this function to hide all the sheets except one particular sheet.
We have various sheets, as follows in our Excel.
Below is the sample code to hide all sheets except one particular sheet.
Code:
Sub NOT_Example3() Dim Ws As Worksheet For Each Ws In ActiveWorkbook.Worksheets If Not (Ws.Name = "Data Sheet") Then Ws.Visible = xlSheetVeryHideen End If Next Ws End Sub
The above code hides all the worksheets except the worksheet “Data Sheet.”
You can use this VBA code to hideVBA columns need to be hidden for the sheet to convey only the relevant information. To hide a column, simply set the property value to ‘TRUE’; to unhide the column, set the property value to ‘FALSE’.read more all the sheets except one particular sheet by changing the sheet name to your sheet name.
For how we can also unhide sheets in excelThere are different methods to Unhide Sheets in Excel as per the need to unhide all, all except one, multiple, or a particular worksheet. You can use Right Click, Excel Shortcut Key, or write a VBA code in Excel. read more. The below code will unhide all the sheets except the sheet name “Data Sheet.”
Code:
Sub NOT_Example4() Dim Ws As Worksheet For Each Ws In ActiveWorkbook.Worksheets If Not (Ws.Name = "Data Sheet") Then Ws.Visible = xlSheetVisible End If Next Ws End Sub
The below code will unhide only the sheet name “Data Sheet.”
Code:
Sub NOT_Example3() Dim Ws As Worksheet For Each Ws In ActiveWorkbook.Worksheets If Not (Ws.Name <> "Data Sheet") Then Ws.Visible = xlSheetVisible End If Next Ws End Sub
Recommended Articles
This article has been a guide to VBA Not Function. Here, we discuss the working of the Not function, how to use it with the IF function, and practical examples and downloadable templates. Below are some useful articles related to VBA: –
- VBA If Else
- IF NOT in VBA
- For Each Loop in Excel VBA
- GoTo in VBA
VBA NOT function in Excel is categorized as a logical function in VBA. It is a built-in function in MS Office Excel VBA. This function returns TRUE, if a condition is FALSE. And it returns FALSE, if a condition is TRUE. This is one of the most used logical operator. It works like an inverse function. It returns a Boolean value either True or False.
We can use this function as a worksheet function and also use in VBA. This function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA NOT function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the NOT function, where we can use this VBA NOT function and real-time examples.
Table of Contents:
- Objective
- Syntax of VBA NOT Function
- Parameters or Arguments
- Where we can apply or use VBA NOT Function?
- Example 1: VBA NOT Function example(False)
- Example 2: VBA NOT Function example(TRUE)
- Example 3: Check an inverse of TRUE
- Example 4: Check an inverse of FALSE
- Instructions to Run VBA Macro Code
- Other Useful Resources
The syntax of the VBA NOT function is
NOT (Condition/Expression)
The VBA NOT function returns a Boolean value either True or False. It returns FALSE, if a condition is TRUE. And it returns TRUE, if a condition is FALSE.
Parameters or Arguments
The NOT function contains a condition.
Where
Condition: It is a required parameter. Here we evaluate specified condition and returns TRUE or FALSE.
Where we can apply or use VBA NOT Function?
We can use this VBA NOT function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.
Example 1: Example on VBA NOT Function(FALSE)
Here is a simple example of the VBA NOT function. This below example macro checks a specified condition is TRUE or FALSE. The output of below macro is FALSE.
'Example on VBA NOT Function(FALSE) Sub VBA_NOT_Function_Ex1() If Not (0 = 0) Then MsgBox "Result :" & True, vbInformation, "VBA NOT Function" Else MsgBox "Result :" & False, vbInformation, "VBA NOT Function" End If End Sub
Output: Here is the screen shot of the first example output.
Example 2: Example on VBA NOT Function(TRUE)
Here is a another example of the VBA NOT function. This below example macro checks a specified condition is TRUE or FALSE. The output of below macro is TRUE.
'Example on VBA NOT Function(TRUE) Sub VBA_NOT_Function_Ex2() If Not (0 = 1) Then MsgBox "Result :" & True, vbInformation, "VBA NOT Function" Else MsgBox "Result :" & False, vbInformation, "VBA NOT Function" End If End Sub
Output: Here is the screen shot of the second example output.
Example 3: Check an inverse of TRUE
Here is a simple example of the VBA NOT function. This below example macro checks for an inverse value. The output of below macro is FALSE.
'Check an inverse of TRUE Sub VBA_NOT_Function_Ex3() sOutput = Not (True) MsgBox "Result :" & sOutput, vbInformation, "VBA NOT Function" End Sub
Output:Here is the screen shot of the third example output.
Example 4: Check an inverse of FALSE
Here is a simple example of the VBA NOT function. This below example macro checks for an inverse value. The output of below macro is TRUE.
'Check an inverse of FALSE Sub VBA_NOT_Function_Ex4() sOutput = Not (False) MsgBox "Result :" & sOutput, vbInformation, "VBA NOT Function" End Sub
Output:Here is the screen shot of the fourth example output.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
Операторы, использующиеся в VBA Excel для отрицания и сравнения логических выражений. Синтаксис, принимаемые значения, приоритет логических операторов.
Оператор «Not»
«Not» – это оператор логического отрицания (инверсия), который возвращает True, если условие является ложным, и, наоборот, возвращает False, если условие является истинным.
Синтаксис:
Таблица значений:
Условие | Результат |
---|---|
True | False |
False | True |
Оператор «And»
«And» – это оператор логического умножения (логическое И, конъюнкция), который возвращает значение True, если оба условия являются истинными.
Синтаксис:
Результат = Условие1 And Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Оператор «Or»
«Or» – это оператор логического сложения (логическое ИЛИ, дизъюнкция), который возвращает значение True, если одно из двух условий является истинным, или оба условия являются истинными.
Синтаксис:
Результат = Условие1 Or Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Оператор «Xor»
«Xor» – это оператор логического исключения (исключающая дизъюнкция), который возвращает значение True, если только одно из двух условий является истинным.
Синтаксис:
Результат = Условие1 Xor Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | False |
True | False | True |
False | True | True |
False | False | False |
Оператор «Eqv»
«Eqv» – это оператор логической эквивалентности (тождество, равенство), который возвращает True, если оба условия имеют одинаковое значение.
Синтаксис:
Результат = Условие1 Eqv Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | True |
Оператор «Imp»
«Imp» – это оператор логической импликации, который возвращает значение False, если первое (левое) условие является истинным, а второе (правое) условие является ложным, в остальных случаях возвращает True.
Синтаксис:
Результат = Условие1 Imp Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | True |
False | False | True |
Приоритет логических операторов
Приоритет определяет очередность выполнения операторов в одном выражении. Очередность выполнения логических операторов в VBA Excel следующая:
- «Not» – логическое отрицание;
- «And» – логическое И;
- «Or» – логическое ИЛИ;
- «Xor» – логическое исключение;
- «Eqv» – логическая эквивалентность;
- «Imp» – логическая импликация.
In this Article
- Using the And Logical Operator
- Using the Or Logical Operator
- Using the Not Logical Operator
- Using the Xor Logical Operator
- Is Operator
- Like Operator
VBA allows you to use the logical operators And, Or, Not, Xor to compare values. The operators are considered “Boolean”, which means they return True or False as a result.
If you want to learn how to compare strings, click here: VBA Compare Strings – StrComp
If you want to learn how to use comparison operators, click here: VBA Comparison Operators – Not Equal to & More
Using the And Logical Operator
The And logical operator compares two or more conditions. If all the conditions are true, the operator will return True. If at least one of the conditions is not true, the operator will return False. Here is an example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 5
If intA = 5 And intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if both intA and intB are equal to 5. If this is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set values of intA and intB to 5:
intA = 5
intB = 5
After that, we use the And operator in the If statement to check if the values are equal to 5:
If intA = 5 And intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As both variables are equal to 5, the blnResult returns True:
Image 1. Using the And logical operator in VBA
Using the Or Logical Operator
The Or logical operator compares two or more conditions. If at least one of the conditions is true, it will return True. If none of the conditions are true, the operator will return False. Here is the code for the example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 10
If intA = 5 Or intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if both intA is equal to 5. or intB is equal to 10. If any of these conditions is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5 and intB to 10:
intA = 5
intB = 10
After that, we use the Or operator in the If statement to check if any of the values is equal to 5:
If intA = 5 Or intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5, the blnResult returns True:
Image 2. Using the Or logical operator in VBA
Using the Not Logical Operator
The Not logical operator checks one or more conditions. If the conditions are true, the operator returns False. Otherwise, it returns True. Here is the code for the example:
Dim intA As Integer
Dim blnResult As Boolean
intA = 5
If Not (intA = 6) Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if the value of intA is not equal to 6. If intA is different than 6, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5:
intA = 5
After that, we use the Not operator in the If statement to check if the value of intA is different than 6:
If Not (intA = 6) Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5, the blnResult returns True:
Image 3. Using the Not logical operator in VBA
Using the Xor Logical Operator
The Xor logical operator compares two or more conditions. If exactly one of the conditions is true, it will return True. If none of the conditions are true, or more than one are true, it will return False. Here is the code for the example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 10
If intA = 5 Xor intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if exactly one of the values (intA or IntB) are equal to 5. If only one condition is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5 and intB to 10:
intA = 5
intB = 10
After that, we use the Or operator in the If statement to check if any of the values is equal to 5:
If intA = 5 Xor intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5 and intB is 10, the blnResult returns True:
Image 4. Using the Xor logical operator in VBA
Is Operator
The Is Operator tests if two object variables store the same object.
Let’s look at an example. Here we will assign two worksheets to worksheet objects rng1 and rng2, testing if the two worksheet objects store the same worksheet:
Sub CompareObjects()
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
If ws1 Is ws2 Then
MsgBox "Same WS"
Else
MsgBox "Different WSs"
End If
End Sub
Of course the worksheet objects are not the same, so “Different WSs” is returned.
Like Operator
The Like Operator can compare two strings for inexact matches. This example will test if a string starts with “Mr.”
Sub LikeDemo()
Dim strName As String
Dim blnResult As Boolean
strName = "Mr. Michael James"
If strName Like "Mr*" Then
blnResult = True
Else
blnResult = False
End If
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!