Excel vba if not text

Main VBA IF NOT

VBA IF Not

In any programming language, we have logical operators AND OR and NOT. Every operator has a specific function to do. AND combines two or more statements and return values true if every one of the statements is true where is in OR operator if any one of the statements is true the value is true. The NOT operator is a different thing. NOT operator negates the given statement. We use these logical operators with IF statements in our day to day data analysis. If we use IF NOT statement in VBA consider this as an inverse function.

We have discussed above that we use the logical operators with if statements. In this article, we will use NOT operator with the if statement. I said earlier that IF NOT statement in VBA is also considered as an inverse function. Why is that because if the condition is true it returns false and if the condition is false it returns true. Have a look below,

IF A>B equals to IF NOT B>A

Both the if statements above are identical how? In the first statement if A is greater than B then the next statement is executed and in the next, if not statement means if B is not greater than A which in itself means A is greater than B.

The most simple way to understand IF NOT statement should be as follows:

If True Then
If NOT false Then

Or we can say that

If False then
IF NOT True then

Both the statements in Comparison 1 and Comparison 2 are identical to each other.

Let’s use IF NOT function in few examples which will make it more clearly for us.

Note: We need to keep in mind that in order to use VBA in excel we first have to enable our developer’s tab from the files tab and then from the options section.

How to Use Excel VBA IF Not?

We will learn how to use a VBA IF Not with few examples in excel.

You can download this VBA IF NOT Excel Template here – VBA IF NOT Excel Template

Example #1 – VBA IF Not

Follow the below steps to use IF NOT in Excel VBA.

For example, I have two values in sheet 1 in cell A1 and B1. Have a look at them below,

VBA IF NOT Example 1

What I want to do is compare these two values which one is greater using IF NOT statement in VBA.

Step 1: Go to the developer’s tab and then click on Visual Basic to open the VB Editor.

VBA IF NOT Example 1.1

Step 2: Insert a module from the insert tab in the VB Editor. Double click on the module we just inserted to open another window where we are going to write our code.

VBA IF NOT Module

Step 3: Every VBA code starts with a sub-function as below,

Code:

Sub Sample()

End Sub

VBA IF NOT Example 1.2

Step 4: Declare two variables as integers which will store our values from cell A1 and B1.

Code:

Sub Sample()

Dim A, B As Integer

End Sub

VBA IF NOT Example 1.3

Step 5: To assign values to these variables we need to activate the worksheet first by the following code.

Code:

Sub Sample()

Dim A, B As Integer
Worksheets("Sheet1").Activate

End Sub

VBA IF NOT Example 1.4

Step 6: Now we will assign these variables the values of A1 and B1.

Code:

Sub Sample()

Dim A, B As Integer
Worksheets("Sheet1").Activate
A = Range("A1")
B = Range("B1")

End Sub

VBA IF NOT Example 1.5

Step 7: Let us compare both the variables using IF NOT statement by the following code,

Code:

Sub Sample()

Dim A, B As Integer
Worksheets("Sheet1").Activate
A = Range("A1")
B = Range("B1")
If Not A > B Then
MsgBox "B is greater than A"
Else
MsgBox "A is greater than B"
End If

End Sub

VBA IF NOT Example 1.6

Step 8: Run the above code from the run button in VBA or we can press the F5 button to do the same. We will get the following result.

VBA IF ELSE 1

Step 9: Let us inverse the values of A and B and again run the code to see the following result.

VBA IF ELSE 2

In the first execution, A was greater than B but we compared IF NOT A>B, Initially, the condition was true so it displayed the result for False statement i.e. A is greater than B and vice versa for execution second.

Example #2 – VBA IF Not

In the first example we compared integers, let us compare strings in this example with IF NOT statement in VBA. In the same sheet1, we have two strings in cell A3 and B3 as follows,

VBA IF NOT Example 2.1

Let us compare both the strings using IF NOT Statement.

Step 1: To open VB Editor first click on Developer’s Tab and then click on Visual Basic.

VBA IF NOT Example 2.2

Step 2: In the same module, we inserted above double click on it to start writing the second code.

Module 2

Step 3: Declare a sub-function below the code we wrote first.

Code:

Sub Sample1()

End Sub

Sub Sample 1

Step 4: Declare two variables as a string that will store our values from cell A3 and B3.

Code:

Sub Sample1()

Dim A, B As String

End Sub

VBA (Dim A)

Step 5: To assign values to these variables we need to activate the worksheet first by the following code to use its properties.

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate

End Sub

Worksheets

Step 6: Now we will assign these variables the values of A3 and B3.

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate
A = Range("A3")
B = Range("B3")

End Sub

Range

Step 7: Let us compare both the variables using IF NOT statement by the starting the if statement as follows,

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate
A = Range("A3")
B = Range("B3")
If Not A = B Then

End Sub

Compare a and b

Step 8: If A = B condition is true then the above statement will negate it and return the value as false.

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate
A = Range("A3")
B = Range("B3")
If Not A = B Then
MsgBox "Both the strings are not same"

End Sub

Msgbox

Step 9: If both the strings are same i.e. if the result is returned as true display the following message,

Code:

Sub Sample1()

Dim A, B As String
Worksheets("Sheet1").Activate
A = Range("A3")
B = Range("B3")
If Not A = B Then
MsgBox "Both the strings are not same"
Else
MsgBox "Both the Strings are same"
End If

End Sub

Else if

Step 10: Now let us run the above code by pressing the F5 button or from the run button given. Once we run the code we get the following result.

VBA IF ELSE 3

Step 11: Now let us make both the stings in A3 and B3 cell same to see the different result when we run the same code.

VBA IF ELSE 3 gif

In the first execution A was not similar to B but we compared IF NOT A=B, Initially the condition was true so it displayed the result for false statement i.e. both the strings are not same and when both of the strings were same we get the different message as both the strings are same.

Things to Remember

  • IF NOT is a comparison statement.
  • IF NOT negates the value of the condition i.e. if a condition is true it returns false and vice versa.
  • IF NOT statement is basically an inverse function.

Recommended Articles

This has been a guide to VBA If Not. Here we have discussed how to use Excel VBA If Not along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Active Cell
  2. VBA RGB
  3. VBA Transpose
  4. VBA Not
Date yes Add (Subtract) Days to a Date Concatenate Dates Convert Date to Number Convert Date to Text Month Name to Number Create Date Range from Dates Day Number of Year Month Name from Date First Day of Month Add (Subtract) Weeks to a Date If Functions with Dates Max Date Number of Days Between Dates Number of Days in a Month Number of Weeks Between Dates Number of Years Between Dates Split Date & Time into Separate Cells Countdown Remaining Days Insert Dates Random Date Generator Using Dynamic Ranges — Year to Date Values Add (Subtract) Years to a Date Date Formula Examples Extract Day from Date Get Day Name from Date Count Days Left in Month / Year Count Workdays Left in Month / Year Get Last Day of Month Last Business Day of Month / Year Number of Work / Business Days in Month Weekday Abbreviations Auto Populate Dates Number of Months Between Dates Quarter from a Date Years of Service Change Date Format Compare Dates Time yes Add (Subtract) Hours to Time Add (Subtract) Minutes to Time Add (Subtract) Seconds to Time Add Up time (Total Time) Time Differences Change Time Format Convert Minutes to Hours Convert Time to Decimal Convert Time to Hours Convert Time to Minutes Convert Time to Seconds Military Time Round Time to Nearest 15 Minutes Overtime Calculator Number of Hours Between Times Convert Seconds to Minutes, Hours, or Time Count Hours Worked Time Differences Time Format — Show Minutes Seconds Text yes Add Commas to Cells Get First Word from Text Capitalize First Letter Clean & Format Phone #s Remove Extra Trailing / Leading Spaces Add Spaces to Cell Assign Number Value to Text Combine Cells with Comma Combine First and Last Names Convert Text String to Date Convert Text to Number Extract Text From Cell Get Last Word Remove Unwated Characters Extract Text Before or After Character How to Split Text String by Space, Comma, & More Remove Special Characters Remove First Characters from Left Substitute Multiple Values Switch First & Last Names w/ Commas Remove Specific Text from a Cell Extract Text Between Characters (Ex. Parenthesis) Add Leading Zeros to a Number Remove Line Breaks from Text Remove all Numbers from Text Reverse Text Remove Non-Numeric Characters Remove Last Character(s) From Right Separate First and Last Names Separate Text & Numbers Round yes Round Formulas Round Price to Nearest Dollar or Cent Round to Nearest 10, 100, or 1000 Round to Nearest 5 or .5 Round Percentages Round to Significant Figures Count yes Count Blank and Non-blank Cells Count Cells Between Two Numbers Count Cells not Equal to Count if Cells are in Range Count Times Word Appears in Cell Count Words in Cell Count Specific Characters in Column Count Total Number of Characters in Column Count Cells that Equal one of two Results Count Cells that do not Contain Count Cells that Contain Specific Text Count Unique Values in Range Countif — Multiple Criteria Count Total Number of Cells in Range Count Cells with Any Text Count Total Cells in a Table Lookup yes Two Dimensional VLOOKUP VLOOKUP Simple Example Vlookup — Multiple Matches Case Sensitive Lookup Case Sensitive VLOOKUP Sum if — VLOOKUP Case Sensitive Lookup Case Sensitive VLOOKUP Find Duplicates w/ VLOOKUP or MATCH INDEX MATCH MATCH Lookup — Return Cell Address (Not Value) Lookup Last Value in Column or Row Reverse VLOOKUP (Right to Left) Risk Score Bucket with VLOOKUP Sum with a VLOOKUP Function VLOOKUP & INDIRECT VLOOKUP Concatenate VLOOKUP Contains (Partial Match) 17 Reasons Why Your XLOOKUP is Not Working Double (Nested) XLOOKUP — Dynamic Columns IFERROR (& IFNA) XLOOKUP Lookup Min / Max Value Nested VLOOKUP Top 11 Alternatives to VLOOKUP (Updated 2022!) VLOOKUP – Dynamic Column Reference VLOOKUP – Fix #N/A Error VLOOKUP – Multiple Sheets at Once VLOOKUP & HLOOKUP Combined VLOOKUP & MATCH Combined VLOOKUP Between Worksheets or Spreadsheets VLOOKUP Duplicate Values VLOOKUP Letter Grades VLOOKUP Return Multiple Columns VLOOKUP Returns 0? Return Blank Instead VLOOKUP w/o #N/A Error XLOOKUP Multiple Sheets at Once XLOOKUP Between Worksheets or Spreadsheets XLOOKUP by Date XLOOKUP Duplicate Values XLOOKUP Multiple Criteria XLOOKUP Return Multiple Columns XLOOKUP Returns 0? Return Blank Instead XLOOKUP Text XLOOKUP with IF XLOOKUP With If Statement Misc. yes Sort Multiple Columns Use Cell Value in Formula Percentage Change Between Numbers Percentage Breakdown Rank Values Add Spaces to Cell CAGR Formula Average Time Decimal Part of Number Integer Part of a Number Compare Items in a List Dealing with NA() Errors Get Worksheet Name Wildcard Characters Hyperlink to Current Folder Compound Interest Formula Percentage Increase Create Random Groups Sort with the Small and Large Functions Non-volatile Function Alternatives Decrease a Number by a Percentage Calculate Percent Variance Profit Margin Calculator Convert Column Number to Letter Get Full Address of Named Range Insert File Name Insert Path Latitute / Longitude Functions Replace Negative Values Reverse List Range Convert State Name to Abbreviation Create Dynamic Hyperlinks Custom Sort List with Formula Data Validation — Custom Formulas Dynamic Sheet Reference (INDIRECT) Reference Cell in Another Sheet or Workbook Get Cell Value by Address Get Worksheet Name Increment Cell Reference List Sheet Names List Skipped Numbers in Sequence Return Address of Max Value in Range Search by Keywords Select Every Other (or Every nth) Row Basics yes Cell Reference Basics — A1, R1C1, 3d, etc. Add Up (Sum) Entire Column or Row Into to Dynamic Array Formulas Conversions yes Convert Time Zones Convert Celsius to Fahrenheit Convert Pounds to Kilograms Convert Time to Unix Time Convert Feet to Meters Convert Centimeters to Inches Convert Kilometers to Miles Convert Inches to Feet Convert Date to Julian Format Convert Column Letter to Number Tests yes Test if a Range Contains any Text Test if any Cell in Range is Number Test if a Cell Contains a Specific Value Test if Cell Contains Any Number Test if Cell Contains Specific Number Test if Cell is Number or Text If yes Percentile If Subtotal If Sumproduct If Large If and Small If Median If Concatentate If Max If Rank If TEXTJOIN If Sum yes Sum if — Begins With / Ends With Sum if — Month or Year to Date Sum if — By Year Sum if — Blank / Non-Blank Sum if — Horizontal Sum Count / Sum If — Cell Color INDIRECT Sum Sum If — Across Multiple Sheets Sum If — By Month Sum If — Cells Not Equal To Sum If — Not Blank Sum if — Between Values Sum If — Week Number Sum Text Sum if — By Category or Group Sum if — Cell Contains Specific Text (Wildcards) Sum if — Date Rnage Sum if — Dates Equal Sum if — Day of Week Sum if — Greater Than Sum if — Less Than Average yes Average Non-Zero Values Average If — Not Blank Average — Ignore 0 Average — Ignore Errors Math yes Multiplication Table Cube Roots nth Roots Square Numbers Square Roots Calculations yes Calculate a Ratio Calculate Age KILLLLLLL Calculate Loan Payments GPA Formula Calculate VAT Tax How to Grade Formulas Find yes Find a Number in a Column / Workbook Find Most Frequent Numbers Find Smallest n Values Find nth Occurance of Character in Text Find and Extract Number from String Find Earliest or Latest Date Based on Criteria Find First Cell with Any Value Find Last Row Find Last Row with Data Find Missing Values Find Largest n Values Most Frequent Number Conditional Formatting yes Conditional Format — Dates & Times Conditional Format — Highlight Blank Cells New Functions XLOOKUP Replaces VLOOKUP, HLOOKUP, and INDEX / MATCH Logical yes AND Checks whether all conditions are met. TRUE/FALSE IF If condition is met, do something, if not, do something else. IFERROR If result is an error then do something else. NOT Changes TRUE to FALSE and FALSE to TRUE. OR Checks whether any conditions are met. TRUE/FALSE XOR Checks whether one and only one condition is met. TRUE/FALSE Lookup & Reference yes FALSE The logical value: FALSE. TRUE The logical value: TRUE. ADDRESS Returns a cell address as text. AREAS Returns the number of areas in a reference. CHOOSE Chooses a value from a list based on it’s position number. COLUMN Returns the column number of a cell reference. COLUMNS Returns the number of columns in an array. HLOOKUP Lookup a value in the first row and return a value. HYPERLINK Creates a clickable link. INDEX Returns a value based on it’s column and row numbers. INDIRECT Creates a cell reference from text. LOOKUP Looks up values either horizontally or vertically. MATCH Searches for a value in a list and returns its position. OFFSET Creates a reference offset from a starting point. ROW Returns the row number of a cell reference. ROWS Returns the number of rows in an array. TRANSPOSE Flips the oriention of a range of cells. VLOOKUP Lookup a value in the first column and return a value. Date & Time yes DATE Returns a date from year, month, and day. DATEDIF Number of days, months or years between two dates. DATEVALUE Converts a date stored as text into a valid date DAY Returns the day as a number (1-31). DAYS Returns the number of days between two dates. DAYS360 Returns days between 2 dates in a 360 day year. EDATE Returns a date, n months away from a start date. EOMONTH Returns the last day of the month, n months away date. HOUR Returns the hour as a number (0-23). MINUTE Returns the minute as a number (0-59). MONTH Returns the month as a number (1-12). NETWORKDAYS Number of working days between 2 dates. NETWORKDAYS.INTL Working days between 2 dates, custom weekends. NOW Returns the current date and time. SECOND Returns the second as a number (0-59) TIME Returns the time from a hour, minute, and second. TIMEVALUE Converts a time stored as text into a valid time. TODAY Returns the current date. WEEKDAY Returns the day of the week as a number (1-7). WEEKNUM Returns the week number in a year (1-52). WORKDAY The date n working days from a date. WORKDAY.INTL The date n working days from a date, custom weekends. YEAR Returns the year. YEARFRAC Returns the fraction of a year between 2 dates. Engineering yes CONVERT Convert number from one unit to another. Financial yes FV Calculates the future value. PV Calculates the present value. NPER Calculates the total number of payment periods. PMT Calculates the payment amount. RATE Calculates the interest Rate. NPV Calculates the net present value. IRR The internal rate of return for a set of periodic CFs. XIRR The internal rate of return for a set of non-periodic CFs. PRICE Calculates the price of a bond. YIELD Calculates the bond yield. INTRATE The interest rate of a fully invested security. Information yes CELL Returns information about a cell. ERROR.TYPE Returns a value representing the cell error. ISBLANK Test if cell is blank. TRUE/FALSE ISERR Test if cell value is an error, ignores #N/A. TRUE/FALSE ISERROR Test if cell value is an error. TRUE/FALSE ISEVEN Test if cell value is even. TRUE/FALSE ISFORMULA Test if cell is a formula. TRUE/FALSE ISLOGICAL Test if cell is logical (TRUE or FALSE). TRUE/FALSE ISNA Test if cell value is #N/A. TRUE/FALSE ISNONTEXT Test if cell is not text (blank cells are not text). TRUE/FALSE ISNUMBER Test if cell is a number. TRUE/FALSE ISODD Test if cell value is odd. TRUE/FALSE ISREF Test if cell value is a reference. TRUE/FALSE ISTEXT Test if cell is text. TRUE/FALSE N Converts a value to a number. NA Returns the error: #N/A. TYPE Returns the type of value in a cell. Math yes ABS Calculates the absolute value of a number. AGGREGATE Define and perform calculations for a database or a list. CEILING Rounds a number up, to the nearest specified multiple. COS Returns the cosine of an angle. DEGREES Converts radians to degrees. DSUM Sums database records that meet certain criteria. EVEN Rounds to the nearest even integer. EXP Calculates the exponential value for a given number. FACT Returns the factorial. FLOOR Rounds a number down, to the nearest specified multiple. GCD Returns the greatest common divisor. INT Rounds a number down to the nearest integer. LCM Returns the least common multiple. LN Returns the natural logarithm of a number. LOG Returns the logarithm of a number to a specified base. LOG10 Returns the base-10 logarithm of a number. MOD Returns the remainder after dividing. MROUND Rounds a number to a specified multiple. ODD Rounds to the nearest odd integer. PI The value of PI. POWER Calculates a number raised to a power. PRODUCT Multiplies an array of numbers. QUOTIENT Returns the integer result of division. RADIANS Converts an angle into radians. RAND Calculates a random number between 0 and 1. RANDBETWEEN Calculates a random number between two numbers. ROUND Rounds a number to a specified number of digits. ROUNDDOWN Rounds a number down (towards zero). ROUNDUP Rounds a number up (away from zero). SIGN Returns the sign of a number. SIN Returns the sine of an angle. SQRT Calculates the square root of a number. SUBTOTAL Returns a summary statistic for a series of data. SUM Adds numbers together. SUMIF Sums numbers that meet a criteria. SUMIFS Sums numbers that meet multiple criteria. SUMPRODUCT Multiplies arrays of numbers and sums the resultant array. TAN Returns the tangent of an angle. TRUNC Truncates a number to a specific number of digits. Stats yes AVERAGE Averages numbers. AVERAGEA Averages numbers. Includes text & FALSE =0, TRUE =1. AVERAGEIF Averages numbers that meet a criteria. AVERAGEIFS Averages numbers that meet multiple criteria. CORREL Calculates the correlation of two series. COUNT Counts cells that contain a number. COUNTA Count cells that are non-blank. COUNTBLANK Counts cells that are blank. COUNTIF Counts cells that meet a criteria. COUNTIFS Counts cells that meet multiple criteria. FORECAST Predict future y-values from linear trend line. FREQUENCY Counts values that fall within specified ranges. GROWTH Calculates Y values based on exponential growth. INTERCEPT Calculates the Y intercept for a best-fit line. LARGE Returns the kth largest value. LINEST Returns statistics about a trendline. MAX Returns the largest number. MEDIAN Returns the median number. MIN Returns the smallest number. MODE Returns the most common number. PERCENTILE Returns the kth percentile. PERCENTILE.INC Returns the kth percentile. Where k is inclusive. PERCENTILE.EXC Returns the kth percentile. Where k is exclusive. QUARTILE Returns the specified quartile value. QUARTILE.INC Returns the specified quartile value. Inclusive. QUARTILE.EXC Returns the specified quartile value. Exclusive. RANK Rank of a number within a series. RANK.AVG Rank of a number within a series. Averages. RANK.EQ Rank of a number within a series. Top Rank. SLOPE Calculates the slope from linear regression. SMALL Returns the kth smallest value. STDEV Calculates the standard deviation. STDEV.P Calculates the SD of an entire population. STDEV.S Calculates the SD of a sample. STDEVP Calculates the SD of an entire population TREND Calculates Y values based on a trendline. Text yes CHAR Returns a character specified by a code. CLEAN Removes all non-printable characters. CODE Returns the numeric code for a character. CONCATENATE Combines text together. DOLLAR Converts a number to text in currency format. EXACT Test if cells are exactly equal. Case-sensitive. TRUE/FALSE FIND Locates position of text within a cell.Case-sensitive. LEFT Truncates text a number of characters from the left. LEN Counts number of characters in text. LOWER Converts text to lower case. MID Extracts text from the middle of a cell. PROPER Converts text to proper case. REPLACE Replaces text based on it’s location. REPT Repeats text a number of times. RIGHT Truncates text a number of characters from the right. SEARCH Locates position of text within a cell.Not Case-sensitive. SUBSTITUTE Finds and replaces text. Case-sensitive. TEXT Converts a value into text with a specific number format. TRIM Removes all extra spaces from text. UPPER Converts text to upper case. VALUE Converts a number stored as text into a number.

Logical functions are useful for calculations that require multiple conditions or criteria to test. In our earlier articles, we have seen “VBA IF,” “VBA OR,” and “VBA AND” conditions. This article will discuss the “VBA IF NOT” function. Before introducing VBA IF NOT function, let me show you about VBA NOT functionThe VBA NOT function in MS Office Excel VBA is a built-in logical function. If a condition is FALSE, it yields TRUE; otherwise, it returns FALSE. It works as an inverse function.read more first.

Table of contents
  • IF NOT in VBA
    • What is NOT Function in VBA?
    • Examples of NOT & IF Function in VBA?
      • Example #1
      • Example #2
    • NOT with IF Condition:
    • Recommended Articles

What is NOT Function in VBA?

The “NOT” function is one of our logical functions with Excel and VBA. All the logical functions require logical tests to perform and return TRUE if the logical test is correct. If the logical test is incorrect, it will return FALSE.

But “VBA NOT” is the opposite of the other logical function. So, we would say this is the inverse function of logical functions.

The “VBA NOT” function returns “FALSE” if the logical test is correct. If the logical test is incorrect, it will return “TRUE.” Now, look at the syntax of the “VBA NOT” function.

NOT(Logical Test)

It is very simple. First, we need to provide a logical test. Then, the NOT function evaluates the test and returns the result.

VBA-IF-NOT

Examples of NOT & IF Function in VBA?

Below are the examples of using the IF and NOT function in excelNOT 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 VBA.

You can download this VBA IF NOT Excel Template here – VBA IF NOT Excel Template

Example #1

Take a look at the below code for an example.

Code:

Sub NOT_Example()

  Dim k As String

  k = Not (100 = 100)

  MsgBox k

End Sub

In the above code, we have declared the variable as a string.

Dim k As String

Then, for this variable, we have assigned the NOT function with the logical test as 100 = 100.

k = Not (100 = 100)

Then, we have written the code to show the result in the VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more. MsgBox k

Now, we will execute the code and see the result.

VBA IF NOT Example 1

We got the result as “FALSE.”

Now, look back at the logical testA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more. We have provided the logical test as 100 = 100, which is generally TRUE; since we had given the NOT function, we got the result as FALSE. As we said in the beginning, it gives inverse results compared to other logical functions. Since 100 equals 100, it has returned the result as FALSE.

Example #2

Now, we will look at one more example with different numbers.

Code:

Sub NOT_Example()

 Dim k As String

 k = Not (85 = 148)

 MsgBox k

End Sub

The code is the same. The only thing we have changed here is We have changed the logical test from 100 = 100 to 85 = 148.

Now, we will run the code and see what the result is.

Example 2

This time we got the result as TRUE. Now, examine the logical test.

k = Not (85 = 148)

We all know 85 is not equal to the number 148. Since it is not equal, the NOT function has returned the result as TRUE.

NOT with IF Condition:

In Excel or VBA, logical conditions are incomplete without the combination IF condition. Using the IF condition 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
we can do many more things beyond default TRUE or FALSE. For example, we got FALSE and TRUE default results in the above examples. Instead, we can modify the result in our own words.

Look at the below code.

Code:

Sub NOT_Example2()

  Dim Number1 As String
  Dim Number2 As String

  Number1 = 100
  Number2 = 100

  If Not (Number1 = Number2) Then
   MsgBox "Number 1 is not equal to Number 2"
  Else
   MsgBox "Number 1 is equal to Number 2"
  End If

End Sub

We have declared two variables.

Dim Number1 As String & Dim Number2 As String

For these two variables, we have assigned the numbers 100 and 100, respectively.

Number1 = 100 & Number2 = 100

Then, we have attached the IF condition to alter the default TRUE or FALSE for the NOT function. If the result of the NOT function is TRUE, then my result will be as follows.

MsgBox “Number 1 is not equal to Number 2.”

If the NOT function result is FALSE, my result is as follows.

MsgBox “Number 1 is equal to Number 2.”

Now, we will run the code and see what happens.

VBA IF NOT Example 3

We got the result as “Number 1 is equal to Number 2”, so the NOT function has returned the FALSE result to the IF condition. So, the IF condition returned this result.

Like this, we can use the IF condition to do the inverse test.

Recommended Articles

This article has been a guide to VBA IF NOT. Here, we discuss using the IF and NOT function in Excel VBA, examples, and downloadable Excel templates. Below are some useful articles related to VBA: –

  • VBA Replace String
  • VBA If Else Statement
  • VBA AND Function
  • IF OR in VBA

Sub Excel_ISTEXT_Function()

Dim ws As Worksheet

Set ws = Worksheets(«ISTEXT»)

ws.Range(«C5») = Application.WorksheetFunction.IsText(ws.Range(«B5»))
ws.Range(«C6») = Application.WorksheetFunction.IsText(ws.Range(«B6»))
ws.Range(«C7») = Application.WorksheetFunction.IsText(ws.Range(«B7»))
ws.Range(«C8») = Application.WorksheetFunction.IsText(ws.Range(«B8»))
ws.Range(«C9») = Application.WorksheetFunction.IsText(ws.Range(«B9»))

End Sub

OBJECTS
Worksheets: The Worksheets object represents all of the worksheets in a workbook, excluding chart sheets.
Range: The Range object is a representation of a single cell or a range of cells in a worksheet.

PREREQUISITES
Worksheet Name: Have a worksheet named ISTEXT.

ADJUSTABLE PARAMETERS
Output Range: Select the output range by changing the Range references («C5») through to («C9») in the VBA code to any cell in worksheet that doesn’t conflict with the formula.

На чтение 19 мин. Просмотров 24.3k.

VBA If Statement

Пьер Корнель

Угадай, если сможешь, и выбери, если посмеешь

Содержание

  1. Краткое руководство по VBA If Statement
  2. Что такое IF  и зачем оно тебе?
  3. Тестовые данные
  4. Формат операторов VBA If Then
  5. Простой пример If Then
  6. Условия IF
  7. Использование If ElseIf
  8. Использование If Else
  9. Используя If And/If Or
  10. Функция IIF
  11. Использование Select Case
  12. Попробуйте это упражнение

Краткое руководство по VBA If Statement

Описание Формат Пример
If Then If [условие верно] 
Then [действие]
End If
If score = 100 
Then Debug.Print
«Отлично» 
End If
If Else If [условие верно]
Then [действие]
Else [действие]
End If
If score = 100 
Then Debug.Print 
«Отлично» 
Else Debug.Print 
«Попробуй снова» 
End If
If ElseIf If [1 условие верно] 
Then [действие]
ElseIf [2 условие
верно] 
Then [действие]
End If
If score = 100 
Then Debug.Print 
«Отлично» 
ElseIf score > 50 
Then Debug.Print 
«Пройдено» 
ElseIf score <= 50 
Then Debug.Print 
«Попробуй снова» 
End If
Else и ElseIf
(Else должно
идти
после ElseIf’s)
If [1 условие верно] 
Then [действие]
ElseIf [2 условие
верно] 
Then [действие]
Else [действие]
End If
If score = 100 
Then Debug.Print 
«Отлично» 
ElseIf score > 50 
Then Debug.Print 
«Пройдено» 
ElseIf score > 30 
Then Debug.Print 
«Попробуй снова» 
Else Debug.Print 
«Ой» 
End If
If без Endif
(Только одна
строка)
If [условие верно] 
Then [действие]
If value <= 0 
Then value = 0

В следующем коде показан простой пример использования
оператора VBA If

If Sheet1.Range("A1").Value > 5 Then
    Debug.Print "Значение больше 5."
ElseIf Sheet1.Range("A1").Value < 5 Then
    Debug.Print "Значение меньше 5."
Else
    Debug.Print "Значение равно 5."
End If

Что такое IF  и зачем оно тебе?

Оператор VBA If используется, чтобы позволить вашему коду
делать выбор, когда он выполняется.

Вам часто захочется сделать выбор на основе данных, которые
читает ваш макрос.

Например, вы можете захотеть читать только тех учеников, у
которых оценки выше 70. Когда вы читаете каждого учащегося, вы можете
использовать инструкцию If для проверки отметок каждого учащегося.

Важным словом в последнем предложении является проверка. Оператор
If используется для проверки значения, а затем для выполнения задачи на основе
результатов этой проверки.

Тестовые данные

Мы собираемся использовать следующие тестовые данные для
примеров кода в этом посте.

VBA If Sample Data

Формат операторов VBA If Then

Формат оператора If Then следующий

За ключевым словом If следуют условие и ключевое слово Then

Каждый раз, когда вы используете оператор If Then, вы должны использовать соответствующий оператор End If.

Когда условие оценивается как истинное, обрабатываются все
строки между If Then и End If.

If [условие верно] Then
    [строки кода]
    [строки кода]
    [строки кода]
End If

Чтобы сделать ваш код более читабельным, рекомендуется
делать отступы между операторами If Then и End If.

Отступ между If и End If

Отступ означает просто переместить строку кода на одну вкладку вправо. Правило большого пальца состоит в том, чтобы сделать отступ между начальным и конечным операторами, такими как:

Sub … End Sub
If Then … End If
If Then… ElseIf … Else … Endif
For … Next
Do While … Loop
Select Case … End Case

Для отступа в коде вы можете выделить строки для отступа и нажать клавишу Tab. Нажатие клавиш Shift + Tab сделает отступ кода, т.е. переместит его на одну вкладку влево.

Вы также можете использовать значки на панели инструментов Visual Basic для отступа кода.

VBA If

Если вы посмотрите на примеры кода на этом сайте, вы увидите, что код имеет отступ.

Простой пример If Then

Следующий код выводит имена всех студентов с баллами более 50.

Sub ChitatOcenki()
    
    Dim i As Long
    ' Пройдите столбцы отметок
    For i = 2 To 11
        ' Проверьте, больше ли баллов,чем 50
        If Sheet1.Range("C" & i).Value > 50 Then
            ' Напечатайте имя студента в «Immediate Window» (Ctrl + G)
            Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value
        End If
    
    Next
    
End Sub

Результаты:

  • Василий Кочин
  • Максим Бородин
  • Дмитрий Маренин
  • Олеся Клюева
  • Евгений Яшин

Поэкспериментируйте с этим примером и проверьте значение или знак > и посмотрите, как изменились результаты.

Условия IF

Часть кода между ключевыми словами If и Then называется условием. Условие — это утверждение, которое оценивается как истинное или ложное. Они в основном используются с операторами Loops и If. При создании условия вы используете такие знаки, как «>, <, <>,> =, <=, =».

Ниже приведены примеры условий:

Условие Это верно, когда
x < 5 x меньше,чем 5
x <= 5 x меньше, либо равен 5
x > 5 x больше, чем 5
x >= 5 x больше, либо равен 5
x = 5 x равен 5
x <> 5 x не равен 5
x > 5 And x < 10 x больше, чем 5 И x меньше, чем 10
x = 2 Or x >10 x равен 2 ИЛИ x больше,чем 10
Range(«A1») = «Иван» Ячейка A1 содержит текст «Иван»
Range(«A1») <> «Иван» Ячейка A1 не содержит текст «Иван»

Вы могли заметить x = 5, как условие. Не стоит путать с х = 5, при использовании в качестве назначения.

Когда в условии используется «=», это означает, что «левая сторона равна правой стороне».

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

Использование «=» Тип Значение
Loop Until x = 5 Условие Равен ли x пяти
Do While x = 5 Условие Равен ли x пяти
If x = 5 Then Условие Равен ли x пяти
For x = 1 To 5 Присваивание Установите значение х = 1, потом = 2 и т.д.
x = 5 Присваивание Установите х до 5
b = 6 = 5 Присваивание и
условие
Присвойте b
результату условия
6 = 5
x = MyFunc(5,6) Присваивание Присвойте х
значение,
возвращаемое
функцией

Последняя запись в приведенной выше таблице показывает
оператор с двумя равными. Первый знак равенства — это присвоение, а любые
последующие знаки равенства — это условия.

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

[переменная] [=] [оценить эту часть]

Поэтому все, что находится справа от знака равенства, оценивается и результат помещается в переменную. Посмотрите на последние три строки таблицы, как:

[x] [=] [5]

[b] [=] [6 = 5]

[x] [=] [MyFunc (5,6)]

Использование If ElseIf

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

Sub IspElseIf()
    
    If Marks >= 85 Then
        Debug.Print "Высший балл"
    ElseIf Marks >= 75 Then
        Debug.Print "Отлично"
    End If
    
End Sub

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

Если это правда, то печатается «Высший балл», и оператор If заканчивается.

Если оно ложно, то код переходит к следующему ElseIf и
проверяет его состояние.

Давайте поменяемся местами If и ElseIf из последнего
примера. Код теперь выглядит так

Sub IspElseIfNeverno()
    
    ' Этот код неверен, так как ElseIf никогда не будет верным
    If Marks >= 75 Then
        Debug.Print "Отлично"
    ElseIf Marks >= 85 Then
        ' код никогда не достигнет здесь
        Debug.Print "Высший балл"
    End If
    
End Sub

В этом случае мы сначала проверяем значение более 75. Мы никогда не будем печатать «Высший балл», потому что, если значение больше 85, это вызовет первый оператор if.

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

If marks >= 75 And marks < 85 Then
    Debug.Print "Отлично"
ElseIf marks >= 85 And marks <= 100 Then
    Debug.Print "Высший балл"
End If

Давайте расширим оригинальный код. Вы можете использовать столько операторов ElseIf, сколько захотите. Мы добавим еще несколько, чтобы учесть все наши классификации баллов.

Использование If Else

Утверждение Else используется, как ловушка для всех. Это в основном означает «если бы не было условий» или «все остальное». В предыдущем примере кода мы не включили оператор печати для метки сбоя. Мы можем добавить это, используя Else.

Sub IspElse()
    
    If Marks >= 85 Then
        Debug.Print "Высший балл"
    ElseIf Marks >= 75 Then
        Debug.Print "Отлично"
    ElseIf Marks >= 55 Then
        Debug.Print "Хорошо"
    ElseIf Marks >= 40 Then
        Debug.Print "Удовлетворительно"
    Else
        ' Для всех других оценок
        Debug.Print "Незачет"
    End If
    
End Sub

Так что, если это не один из других типов, то это провал.

Давайте напишем некоторый код с помощью наших примеров
данных и распечатаем студента и его классификацию.

Sub DobClass()
    
    ' получить последнюю строку
    Dim startRow As Long, lastRow As Long
    startRow = 2
    lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, Marks As Long
    Dim sClass As String

    ' Пройдите столбцы отметок
    For i = startRow To lastRow
        Marks = Sheet1.Range("C" & i).Value
        ' Проверьте отметки и классифицируйте соответственно
        If Marks >= 85 Then
            sClass = "Высший балл"
        ElseIf Marks >= 75 Then
            sClass = "Отлично"
        ElseIf Marks >= 55 Then
            sClass = "Хорошо"
        ElseIf Marks >= 40 Then
            sClass = "Удовлетворительно"
        Else
            ' Для всех других оценок
            sClass = "Незачет"
        End If
    
        ' Запишите класс в столбец E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

Результаты выглядят так: в столбце E — классификация баллов

VBA If ElseIf Class

Используя If And/If Or

В выражении If может быть несколько условий. Ключевые слова VBA And и Or позволяют использовать несколько условий.

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

Давайте снова посмотрим на наши примеры данных. Теперь мы
хотим напечатать всех студентов, которые набрали от 50 до 80 баллов.

Мы используем Аnd, чтобы добавить дополнительное условие. Код гласит: если оценка больше или равна 50 и меньше 75, напечатайте имя студента.

Sub ProverkaStrokiOcenok()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Хранить оценки для текущего студента
        marks = Sheet1.Range("C" & i).Value
        
        ' Проверьте, если отметки больше 50 и меньше 75
        If marks >= 50 And marks < 80 Then
             ' Напечатайте имя и фамилию в Immediate window (Ctrl+G)
             Debug.Print Sheet1.Range("A" & i).Value & Sheet1.Range("B" & i).Value
        End If
    
    Next

End Sub

Вывести имя и фамилию в результаты:

  • Дмитрий Маренин
  • Олеся Клюева
  • Евгений Яшин

В нашем следующем примере мы хотим знать, кто из студентов сдавал историю или геометрию. Таким образом, в данном случае мы говорим, изучал ли студент «История» ИЛИ изучал ли он «Геометрия» (Ctrl+G).

Sub ChitatObektOcenki()
    
    Dim i As Long, marks As Long
    
    ' Пройдите столбцы отметок
    For i = 2 To 11
        marks = Sheet1.Range("D" & i).Value
        ' Проверьте, если отметки больше 50 и меньше 80
        If marks = "История" Or marks = "Геометрия" Then
            ' Напечатайте имя и фамилию в Immediate window (Ctrl+G)
            Debug.Print Sheet1.Range("A" & i).Value & " " & Sheet1.Range("B" & i).Value
        End If
    
    Next
    
End Sub

Результаты:

  • Василий Кочин
  • Александр Грохотов
  • Дмитрий Маренин
  • Николай Куликов
  • Олеся Клюева
  • Наталия Теплых
  • Дмитрий Андреев

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

Использование IF AND

And работает следующим образом:

Условие 1 Условие 2 Результат
ИСТИНА ИСТИНА ИСТИНА
ИСТИНА ЛОЖЬ ЛОЖЬ
ЛОЖЬ ИСТИНА ЛОЖЬ
ЛОЖЬ ЛОЖЬ ЛОЖЬ

Что вы заметите, так это то, что And верно только тогда, когда все условия выполняются.

Использование IF OR

Ключевое слово OR работает следующим образом

Условие 1 Условие 2 Результат
ИСТИНА ИСТИНА ИСТИНА
ИСТИНА ЛОЖЬ ИСТИНА
ЛОЖЬ ИСТИНА ИСТИНА
ЛОЖЬ ЛОЖЬ ЛОЖЬ

Что вы заметите, так это то, что OR ложно, только когда все условия ложны.

Смешивание And и Or может затруднить чтение кода и привести к ошибкам. Использование скобок может сделать условия более понятными.

Sub OrSAnd()
    
 Dim subject As String, marks As Long
 subject = "История"
 marks = 5
    
 If (subject = "Геометрия" Or subject = "История") And marks >= 6 Then
     Debug.Print "ИСТИНА"
 Else
     Debug.Print "ЛОЖЬ"
 End If
    
End Sub

Использование IF NOT

Также есть оператор NOT. Он возвращает противоположный результат условия.

Условие Результат
ИСТИНА ЛОЖЬ
ЛОЖЬ ИСТИНА

Следующие две строки кода эквивалентны.

If marks < 40 Then 
If Not marks >= 40 Then

так же, как и

If True Then 
If Not False Then 

и

If False Then 
If Not True Then 

Помещение условия в круглые скобки облегчает чтение кода

If Not (marks >= 40) Then

Распространенное использование Not — при проверке, был ли установлен объект. Возьмите Worksheet для примера. Здесь мы объявляем рабочий лист.

Dim mySheet As Worksheet
' Некоторый код здесь

Мы хотим проверить действительность mySheet перед его использованием. Мы можем проверить, если это Nothing.

If mySheet Is Nothing Then

Нет способа проверить, является ли это чем-то, поскольку есть много разных способов, которым это может быть что-то. Поэтому мы используем NOT с Nothing.

If Not mySheet Is Nothing Then

Если вы находите это немного запутанным, вы можете использовать круглые скобки, как здесь

If Not (mySheet Is Nothing) Then

Функция IIF

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

= ЕСЛИ (F2 =»»,»», F1 / F2)

Формат

= If (условие, действие, если ИСТИНА, действие, если ЛОЖЬ).

VBA имеет функцию IIf, которая работает так же. Давайте посмотрим на примере. В следующем коде мы используем IIf для проверки значения переменной val. Если значение больше 10, мы печатаем ИСТИНА, в противном случае мы печатаем ЛОЖЬ.

Sub ProveritVal()
 
    Dim result As Boolean
    Dim val As Long
    
    ' Печатает ИСТИНА
    val = 11
    result = IIf(val > 10, ИСТИНА, ЛОЖЬ)
    Debug.Print result
    
    ' печатает ЛОЖЬ
    val = 5
    result = IIf(val > 10, ИСТИНА, ЛОЖЬ)
    Debug.Print result
    
End Sub

В нашем следующем примере мы хотим распечатать «Удовлетворитеьно» или «Незачет» рядом с каждым студентом в зависимости от их баллов. В первом фрагменте кода мы будем использовать обычный оператор VBA If, чтобы сделать это.

Sub ProveritDiapazonOcenok()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Хранить оценки для текущего студента
        marks = Sheet1.Range("C" & i).Value
        
        ' Проверьте, прошел ли студент или нет
        If marks >= 40 Then
             ' Запишите имена для столбца F
             Sheet1.Range("E" & i) = "Удовлетворительно"
        Else
             Sheet1.Range("E" & i) = "Незачет"
        End If
    
    Next

End Sub

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

Sub ProveritDiapazonOcenok ()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Хранить оценки для текущего студента
        marks = Sheet1.Range("C" & i)
        
        ' Проверьте, прошел ли студент или нет
        Sheet1.Range("E" & i).Value = IIf(marks >= 40,"Удовлетворительно","Незачет")
    
    Next

End Sub

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

Использование Nested IIf

Вы также можете вкладывать IIf-операторы, как в Excel. Это означает использование результата одного IIf с другим. Давайте добавим еще один тип результата в наши предыдущие примеры. Теперь мы хотим напечатать «Отлично», «Удовлетворительно» или «Незачетт» для каждого студента.

Используя обычный VBA, мы сделали бы это так

Sub ProveritRezultatiTip2()

    Dim i As Long, marks As Long
    For i = 2 To 11
        
        ' Хранить оценки для текущего студента
        marks = Sheet1.Range("C" & i).Value
        
        If marks >= 75 Then
             Sheet1.Range("E" & i).Value = "Отлично"
        ElseIf marks >= 40 Then
             ' Запишите имена для столбца F
             Sheet1.Range("E" & i).Value = "Удовлетворительно"
        Else
             Sheet1.Range("E" & i).Value = "Незачет"
        End If
    
    Next

End Sub

Используя вложенные IIfs, мы могли бы сделать это так

Sub IspNestedIIF()

Dim i As Long, marks As Long, result As String
For i = 2 To 11
    
marks = Sheet1.Range("C" & i).Value
result = IIf(marks >= 55,"Хорошо",IIf(marks >= 40,"Удовлетворительно","Незачет"))

Sheet1.Range("E" & i).Value = result

Next

End Sub

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

Чего нужно остерегаться

Важно понимать, что функция IIf всегда оценивает как
Истинную, так и Ложную части выражения независимо от условия.

В следующем примере мы хотим разделить по баллам, когда он не равен нулю. Если он равен нулю, мы хотим вернуть ноль.

marks = 0
total = IIf(marks = 0, 0, 60 / marks)

Однако, когда отметки равны нулю, код выдаст ошибку «Делить на ноль». Это потому, что он оценивает как Истинные, так и Ложные утверждения. Здесь ложное утверждение, т.е. (60 / Marks), оценивается как ошибка, потому что отметки равны нулю.

Если мы используем нормальный оператор IF, он будет
запускать только соответствующую строку.

marks = 0
If marks = 0 Then
    'Выполняет эту строку только когда отметки равны нулю
    total = 0
Else
    'Выполняет только эту строку, когда отметки не равны нулю
    total = 60 / marks
End If

Это также означает, что если у вас есть функции для ИСТИНА и ЛОЖЬ, то обе будут выполнены. Таким образом, IIF будет запускать обе функции, даже если он использует только одно возвращаемое значение. Например:

' Обе функции будут выполняться каждый раз
total = IIf(marks = 0, Func1, Func2)

IF против IIf

Так что лучше?

В этом случае вы можете видеть, что IIf короче для написания и аккуратнее. Однако если условия усложняются, вам лучше использовать обычное выражение If. Недостатком IIf является то, что он недостаточно известен, поэтому другие пользователи могут не понимать его так же, как и код, написанный с помощью обычного оператора if.

Кроме того, как мы обсуждали в последнем разделе, IIF всегда оценивает части ИСТИНА и ЛОЖЬ, поэтому, если вы имеете дело с большим количеством данных, оператор IF будет быстрее.

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

Использование Select Case

Оператор Select Case
— это альтернативный способ написания статистики If с большим количеством ElseIf. Этот тип операторов
вы найдете в большинстве популярных языков программирования, где он называется
оператором Switch. Например,
Java, C #, C ++ и Javascript
имеют оператор switch.

Формат

Select Case [переменная]
    Case [условие 1]
    Case [условие 2]
    Case [условие n]
    Case Else
End Select

Давайте возьмем наш пример DobClass сверху и перепишем его с помощью оператора Select Case.

Sub DobavitClass()
    
    ' получить последнюю строку
    Dim startRow As Long, lastRow As Long
    startRow = 2
    lastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, Marks As Long
    Dim sClass As String

    ' Пройдите столбцы отметок
    For i = startRow To lastRow
        Marks = Sheet1.Range("C" & i).Value
        ' Проверьте отметки и классифицируйте соответственно
        If Marks >= 85 Then
            sClass = "Высший балл"
        ElseIf Marks >= 75 Then
            sClass = "Отлично"
        ElseIf Marks >= 55 Then
            sClass = "Хорошо"
        ElseIf Marks >= 40 Then
            sClass = "Удовлетворительно"
        Else
            ' Для всех других оценок
            sClass = "Незачет"
        End If
    
        ' Запишите класс в столбец E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

Ниже приведен тот же код с использованием оператора Select Case. Главное, что вы заметите, это то, что мы используем “Case 85 to 100” rather than “marks >=85 And marks <=100”. , а не “marks >=85 And marks <=100”.

Sub DobavitClassSSelect()
    
    ' получить первую и последнюю строки
    Dim firstRow As Long, lastRow As Long
    firstRow = 2
    lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row
    
    Dim i As Long, marks As Long
    Dim sClass As String

    ' Пройдите столбцы отметок
    For i = firstRow To lastRow
        marks = Sheet1.Range("C" & i).Value
        ' Проверьте отметки и классифицируйте соответственно
        Select Case marks
        Case 85 To 100
            sClass = "Высший балл"
        Case 75 To 84
            sClass = "Отлично"
        Case 55 To 74
            sClass = "Хорошо"
        Case 40 To 54
            sClass = "Удовлетворительно"
        Case Else
            ' Для всех других оценок
            sClass = "Незачет"
        End Select
        ' Запишите класс в столбец E
        Sheet1.Range("E" & i).Value = sClass
    Next
    
End Sub

Использование Case Is

Вы можете переписать оператор select в том же формате, что и оригинальный ElseIf. Вы можете использовать Is с Case.

Select Case marks
    Case Is >= 85
         sClass = "Высший балл"
    Case Is >= 75
        sClass = "Отлично"
    Case Is >= 55
        sClass = "Хорошо"
    Case Is >= 40
        sClass = "Удовлетворительно"
    Case Else
        ' Для всех других оценок
        sClass = "Незачет"
End Select

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

Sub TestNeskZnach()
    
    Dim marks As Long
    marks = 7
    
    Select Case marks
        Case Is = 5, 7, 9
            Debug.Print True
        Case Else
            Debug.Print False
    End Select
    
End Sub

Попробуйте это упражнение

В этой статье много рассказывали о выражении If. Хороший способ помочь вам понять — это попытаться написать код, используя темы, которые мы рассмотрели. В следующем упражнении используются тестовые данные из этой статьи. Ответ на упражнение ниже.

Мы будем использовать ячейку G1, чтобы написать имя
субъекта.

В колонках от H до L запишите всех студентов, которые имеют оценки по этому предмету. Мы хотим классифицировать их результат как успешный или неудачный. Оценка ниже 40 — неудача, оценка 40 или выше — Зачет.

Колонка H: Имя

Колонка I: Фамилия

Колонка J: Баллы

Колонка H: Предмет

Столбец I: Тип результата — Зачет или Незачет

Если ячейка G1 содержит «Геометрия», то ваш результат должен выглядеть следующим образом:

VBA If Statement

Ответ на упражнение

Следующий код показывает, как выполнить вышеупомянутое упражнение.

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

Sub ZapisatRezultat()
     
    ' Получить тему
    Dim subject As String
    subject = Sheet1.Range("G1").Value
     
    If subject = "" Then
        Exit Sub
    End If
     
    ' Получить первый и последний ряд
    Dim firstRow As Long, lastRow As Long
    firstRow = 2
    lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row
     
    ' Очистить любой существующий вывод
    Sheet1.Range("H:L").ClearContents
     
    ' Отслеживать выходной ряд
    Dim outRow As Long
    outRow = 1
     
    Dim i As Long, marks As Long, rowSubject As String
    ' Прочитать данные
    For i = firstRow To lastRow
        marks = Sheet1.Range("C" & i).Value
        rowSubject = Sheet1.Range("D" & i).Value
        If rowSubject = subject Then
            ' Запишите данные студента, если предмет Геометрия
            Sheet1.Range("A" & i & ":" & "D" & i).Copy
            Sheet1.Range("H" & outRow).PasteSpecial xlPasteValues
             
            ' Запишите Зачет или Незачет
            If marks < 40 Then
                Sheet1.Range("L" & outRow).Value = "Незачет"
            ElseIf marks >= 40 Then
                Sheet1.Range("L" & outRow).Value = "Зачет"
            End If
            ' Переместить вывод в следующую строку
            outRow = outRow + 1
        End If
         
    Next i
     
End Sub

  • VBA ЕСЛИ НЕ

VBA ЕСЛИ НЕ

На любом языке программирования у нас есть логические операторы И ИЛИ и НЕ. У каждого оператора есть определенная функция. AND объединяет два или более операторов и возвращает значения true, если каждое из утверждений истинно, где находится в операторе OR, если любое из утверждений истинно, значение истинно. Оператор НЕ — это другое. Оператор NOT отрицает данное утверждение. Мы используем эти логические операторы с операторами IF в нашем повседневном анализе данных. Если мы используем оператор IF NOT в VBA, рассмотрим это как обратную функцию.

Выше мы обсуждали, что мы используем логические операторы с операторами if. В этой статье мы будем использовать оператор NOT с оператором if. Ранее я говорил, что оператор IF NOT в VBA также рассматривается как обратная функция. Почему, потому что, если условие истинно, оно возвращает ложь, а если условие ложно, оно возвращает истину. Посмотрите ниже,

ЕСЛИ A> B равно IF НЕ B> A

Оба предложения if выше идентичны, как? В первом операторе, если A больше, чем B, выполняется следующий оператор, а в следующем, если не оператор, означает, что B не больше, чем A, что само по себе означает, что A больше, чем B.

Самый простой способ понять утверждение IF NOT должно быть следующим:

 Если верно, то если не ложно, то 

Или мы можем сказать, что

 Если Ложь, тогда ЕСЛИ НЕ Верно 

Оба утверждения в Сравнении 1 и Сравнении 2 идентичны друг другу.

Давайте использовать функцию IF NOT в нескольких примерах, которые сделают ее более понятной для нас.

Примечание : мы должны помнить, что для использования VBA в Excel мы должны сначала включить вкладку нашего разработчика на вкладке файлов, а затем в разделе параметров.

Как использовать Excel VBA, если нет?

Мы научимся использовать VBA IF Not с несколькими примерами в Excel.

Вы можете скачать этот VBA, если не шаблон Excel здесь — VBA, если не шаблон Excel

Пример № 1 — VBA, если нет

Выполните следующие шаги, чтобы использовать ЕСЛИ НЕ в Excel VBA.

Например, у меня есть два значения на листе 1 в ячейках A1 и B1. Посмотрите на них ниже,

То, что я хочу сделать, это сравнить эти два значения, которое больше, используя оператор IF NOT в VBA.

Шаг 1: Перейдите на вкладку разработчика и нажмите Visual Basic, чтобы открыть редактор VB.

Шаг 2: Вставьте модуль из вкладки вставки в VB Editor. Дважды щелкните по модулю, который мы только что вставили, чтобы открыть другое окно, в которое мы собираемся написать наш код.

Шаг 3: Каждый код VBA начинается с подфункции, как показано ниже,

Код:

 Sub Sample () End Sub 

Шаг 4: Объявите две переменные как целые числа, которые будут хранить наши значения из ячеек A1 и B1.

Код:

 Sub Sample () Dim A, B As Integer End Sub 

Шаг 5: Чтобы присвоить значения этим переменным, нам нужно сначала активировать лист с помощью следующего кода.

Код:

 Sub Sample () Dim A, B As Integer Worksheets ("Sheet1"). Активировать End Sub 

Шаг 6: Теперь мы присвоим этим переменным значения A1 и B1.

Код:

 Sub Sample () Dim A, B As Integer Worksheets ("Sheet1"). Активировать A = Range ("A1") B = Range ("B1") End Sub 

Шаг 7: Давайте сравним обе переменные, используя оператор IF NOT с помощью следующего кода:

Код:

 Sub Sample () Dim A, B As Integer Worksheets ("Sheet1"). Активируйте A = Range ("A1") B = Range ("B1") Если не A> B, то MsgBox "B больше, чем A" Иначе MsgBox «A больше, чем B» End If End Sub 

Шаг 8: Запустите приведенный выше код с кнопки запуска в VBA, или мы можем нажать кнопку F5, чтобы сделать то же самое. Мы получим следующий результат.

Шаг 9: Давайте инвертируем значения A и B и снова запустим код, чтобы увидеть следующий результат.

В первом выполнении A было больше, чем B, но мы сравнивали IF NOT A> B, изначально условие было истинным, поэтому оно отображало результат для оператора False, т. Е. A больше, чем B, и наоборот для второго выполнения.

Пример № 2 — VBA, если нет

В первом примере мы сравнили целые числа, давайте сравним строки в этом примере с оператором IF NOT в VBA. В том же листе 1 у нас есть две строки в ячейках A3 и B3 следующим образом:

Давайте сравним обе строки, используя оператор IF NOT.

Шаг 1: Чтобы открыть VB Editor, сначала нажмите вкладку разработчика, а затем нажмите Visual Basic.

Шаг 2: В тот же модуль, который мы вставили выше, дважды щелкните по нему, чтобы начать писать второй код.

Шаг 3: Объявите подфункцию под кодом, который мы написали первым.

Код:

 Sub Sample1 () End Sub 

Шаг 4: Объявите две переменные в виде строки, в которой будут храниться наши значения из ячеек A3 и B3.

Код:

 Sub Sample1 () Dim A, B As String End Sub 

Шаг 5: Чтобы присвоить значения этим переменным, нам нужно сначала активировать лист с помощью следующего кода, чтобы использовать его свойства.

Код:

 Sub Sample1 () Dim A, B As String Worksheets ("Sheet1"). Активировать End Sub 

Шаг 6: Теперь мы присвоим этим переменным значения A3 и B3.

Код:

 Sub Sample1 () Dim A, B As String Worksheet ("Sheet1"). Активировать A = диапазон ("A3") B = диапазон ("B3") End Sub 

Шаг 7: Давайте сравним обе переменные, используя оператор IF NOT, начав оператор if следующим образом:

Код:

 Sub Sample1 () Dim A, B As String Worksheets ("Sheet1"). Активируйте A = Range ("A3") B = Range ("B3"), если не A = B, тогда End Sub 

Шаг 8: Если условие A = B является истинным, то приведенное выше утверждение отрицает его и возвращает значение как ложное.

Код:

 Sub Sample1 () Dim A, B As String Worksheets ("Sheet1"). Активируйте A = Range ("A3") B = Range ("B3") Если не A = B, то MsgBox "Обе строки не совпадают" Конец Sub 

Шаг 9: Если обе строки одинаковы, т. Е. Если результат возвращен как true, отобразите следующее сообщение,

Код:

 Sub Sample1 () Dim A, B As String Worksheets ("Sheet1"). Активируйте A = Range ("A3") B = Range ("B3") Если не A = B, то MsgBox "Обе строки не одинаковы" Иначе MsgBox "Обе строки одинаковы" End If End Sub 

Шаг 10: Теперь давайте запустим приведенный выше код, нажав кнопку F5 или указанную кнопку запуска. Запустив код, мы получим следующий результат.

Шаг 11: Теперь давайте сделаем одинаковые строки в ячейках A3 и B3, чтобы увидеть разные результаты при выполнении одного и того же кода.

В первом исполнении A не было похоже на B, но мы сравнивали IF NOT A = B, изначально условие было истинным, поэтому оно отображало результат для ложного утверждения, т. Е. Обе строки не совпадают, и когда обе строки были одинаковыми, мы получаем разные сообщения, так как обе строки одинаковы.

То, что нужно запомнить

  • ЕСЛИ НЕ является сравнительным утверждением.
  • Если NOT отрицает значение условия, то есть если условие истинно, оно возвращает ложь, и наоборот.
  • Если оператор NOT является в основном обратной функцией.

Рекомендуемые статьи

Это было руководство для VBA, если нет. Здесь мы обсудили, как использовать Excel VBA If Not вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Работа с VBA Active Cell
  2. Удаление строки в VBA
  3. Как использовать Excel VBA Transpose?
  4. Как исправить ошибку 1004 с помощью VBA
  5. VBA не

 

Здравствуйте!  
Вопрос, по сути в заголовке.    
Имеем значения, к примеру: «345» и «3куц» как в коде проще всего определить что можно использовать как число?    
Чет я простых методов не нашел… :(

 

LightZ

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

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

Может я что-то не правильно понял?  
Debug.Print IsNumeric(Cells(1, 1).Value)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Понял ошибку. Я пробовал  Is Numeric.  
Спасибо!

 

LightZ

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

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

Не за что  
Также:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

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

{quote}{login=LightZ}{date=09.07.2012 07:29}{thema=}{post}Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»){/post}{/quote}С этим нужно осторожнее: при пустом значении и дате, получим неверные ответы :-)

 

Ну мне для решения конкретной задачи больше всего походит первый вариант в виде:  
If IsNumeric(Arr(i)) Then a = a + Arr(i)

 

ZVI

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

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

Добрый вечер, Михаил!  
На всякий случай для коллекции, это тоже будет = True:  
Debug.Print IsNumeric(«1d3»), IsNumeric(«1e2»)

 

KuklP

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

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

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

Здравствуйте все. В дополнение, и это тоже:  
Debug.Print Application.IsText(«1d3»), Application.IsText(«1e2»)  
:-)

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

 

KuklP

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

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

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

Забыл еще:  
Debug.Print Application.IsText(«13»), Application.IsText(«12»)

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

 

LightZ

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

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

Так я думаю вряд ли кто-то будет использовать  
с перемененными и константами всё Ок  

  Const x As Long = «111»: Const z As String = «abc»  
Debug.Print Application.IsText(x), Application.IsText(z)  

  False True

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

KuklP

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

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

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

Богдан, вот это — неправильно:  
Const x As Long = «111»  
Правильно:  
Const x As Long = 111  
Экс, да, произведет неявное преобразование, что не есть хорошо. Из-за того, что результат в разных случаях непредсказуем и может привести к ошибкам выполнения:-)  
Попробуй по шагам:  
Const x As Long = «1d3»  
Stop  
И посмотри, чему равен х.

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

 

LightZ

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

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

Серёж, а в чём разница то?  

  Const x As Long = «111»  
Const x As Long = 111

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

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

«111» — строка  
111 — число

 

{quote}{login=ZVI}{date=09.07.2012 09:56}{thema=}{post}Добрый вечер, Михаил!  
На всякий случай для коллекции, это тоже будет = True:  
Debug.Print IsNumeric(«1d3»), IsNumeric(«1e2»){/post}{/quote}  
А почему к «d» и «e» такое «избранное» отношение?  
Проверил другие буквы — везде False

 

LightZ

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

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

{quote}{login=Юрий М}{date=09.07.2012 11:37}{thema=}{post}»111″ — строка  
111 — число{/post}{/quote} Ну это если не объявлять числовую переменную, тогда так

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

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

Богдан, а тогда зачем объявлять заведомо неверно? Об этом Серж и говорит… Если «111», ту нужно и писать: As String. Если хотим числовую переменную — кавычки не нужны. Вот о чём разговор.

 

> А почему к «d» и «e» такое «избранное» отношение?  

  Михаил, это экспоненциальная запись числа. 1d3=1000, 1e2=100.  
В Фортране использование символа E означает тип Single, а D — Double. То есть там 1 — единица целого типа, 1E0 — единица типа Single, 1D0 — единица типа Double.  
VBA воспринимает обе буквы как указание типа Double.  
Попробуйте также в окне Immediate  

  ?isnumeric(«ff»),isnumeric(«&hff»),isnumeric(«&o75»),isnumeric(«&o79»)

 

Я попробовал так: хоть 234е765б + 1 хоть 123d765 + 1 =11 (+25 = 35)  
и вообще, т.е если внутри цифр, сколько бы из не было, стоит одна е или d, то как число это равно 10. но цифры должны быть с обеих сторон.

 

k61

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

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

IsNumeric(«ЧислоИлиЦифра» & Chr(160) & «ЧислоИлиЦифра»)=True  
Chr(160) — пробел.

 

Если данные будут считываться только из ячеек рабочего_листа:  

  Function ValueIsNumber(X) As Boolean  
   Select Case VarType(X)  
   Case vbDouble, vbDate, vbBoolean  
   Case Else  
       Exit Function  
   End Select  
   ValueIsNumber = True  
End Function  

  Если даты или логические не считать числами — удалить vbDate или vbBoolean

 

LightZ

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

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

{quote}{login=Юрий М}{date=10.07.2012 10:40}{thema=}{post}Богдан, а тогда зачем объявлять заведомо неверно? Об этом Серж и говорит… Если «111», ту нужно и писать: As String. Если хотим числовую переменную — кавычки не нужны. Вот о чём разговор.{/post}{/quote}Юрий, я понял.  
По идее в варианте Михаила, данные будут заливаться с листа, т.е. проблем с IsNumeric или же IsText возникнуть не должно, у меня всегда отрабатывали на ура. :)

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

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

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

 

LightZ

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

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

Загвоздочка может произойти только с пробелом или пустой ячейкой, т.к. vba считает, что пустая ячейка это число, а вот с датой проблем нет (false)  

  Dim x As Range  
   For Each x In ActiveSheet.UsedRange  
       If Not Application.Trim(x.Value) = Empty Then Debug.Print IsNumeric(x.Value), x.Value, x.Address  
   Next

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

ran

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

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

Что-то я не улавливаю.  
Если x.Value = Empty, то зачем Application.Trim ?  
Если x.Value <> Empty, то Application.Trim(x.Value) все равно не будет Empty

 

Юрий М

Модератор

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

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

{quote}{login=LightZ}{date=10.07.2012 10:01}{thema=}{post}Загвоздочка может произойти только с пробелом или пустой ячейкой, т.к. vba считает, что пустая ячейка это число, а вот с датой проблем нет {/post}{/quote}Ну как же нет?  
Вот Ваше предложение:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)  
Введите в ячейку дату и проверьте.

 

ZVI

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

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

E — это экспоненциальная форма записи числа  
D — это тоже какая-то архаичная форма числа.  
И то и другое выдаст число As Double, возможно поэтому и D  

  В окне Immediate:  
?2d3 или ?2e3 покадут результат 2000, т.е 2*10^3  
?VarType(2e3)=vbDouble выдаст True  

  Если вписать в VBA-модуле, например, такую строку:  
a = 2d3 или a = 2e3  
то после смещения курсора на другую строку эта преобразуется в    
a = 2000#  
где # в конце означает преобразование числа в Double

 

Павел

Гость

#27

10.07.2012 22:23:57

2 Михаил С  

Цитата
А почему к «d» и «e» такое «избранное» отношение

Точка и знаки «d» и «e» могут быть частью записи числа, не поэтому ли?

 

LightZ

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

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

RAN, воспроизведите макрос:  
Sub tt()  
   With Cells(1, 1)  
       .Value = »   »  
       Debug.Print .Value = Empty, Application.Trim(.Value) = Empty  

                 .Value = Empty  
       Debug.Print .Value = Empty  
   End With  
End Sub  

  Т.е. с помощью Application.Trim(x.Value) убиваю сразу двух зайцев: пустоту и пробел  

  Юрий, я описал про IsNumeric, а с текстом придется учитывать и дату  

     With Cells(1, 1)  
       If Not IsDate(.Value) Then Debug.Print Application.IsText(.Value)  
   End With

Киса, я хочу Вас спросить, как художник — художника: Вы рисовать умеете?

 

Юрий М

Модератор

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

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

{quote}{login=LightZ}{date=10.07.2012 10:29}{thema=}{post}Юрий, я описал про IsNumeric, а с текстом придется учитывать и дату{/post}{/quote}Я реагировал на это:  
Debug.Print IIf(Application.IsText(Cells(1, 1).Value), «Text», «Numeric»)  
Посмотрите — моё сообщение сразу после Вашего :-) Разобрались :-)

 

Михаил С.

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

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

#30

10.07.2012 23:15:44

Такой, казалось бы, простой вопрос, а столько подводных камней! :)  
Для моей задачи подошел самый первый ответ — IsNumeric(a).  
По сути у меня массив примерно 150 столбцов, с столбцы и числовые и тестовые. Нужно строки, удовлетворяющие определенным условиям, сложить, пропуская тест.  
такой кусок кодаЖ  
For ii =  1 To Ubound(Arr, 2)  
if IsNumeric(Arr(i, ii)) Then MiArr(si, ii) = MiArr(si, ii)+Arr(i, ii)  
Next  
Дат у меня нет, но проверил ради интереса — обрабатывает корректно, т.е. пропускает

In VBA, when you use the IF statement, it executes a line of code if the condition you have specified to test is TRUE. But when you use the NOT operator with IF, it checks if the condition you have specified is not TRUE and executes the code based on that. It’s like making the IF statement opposite, TRUE into FALSE and FALSE into TRUE.

Let’s say you want to test if A < B, and if this condition is true IF will return TRUE, right? But when you use IF NOT A < B, it will return FALSE.

Note: NOT is a logical operator.

Examples to use VBA IF NOT

Here’s we will see a simple example to understand it:

Sub myMacro()

Dim A As Range, B As Range
Set A = Range("A1")
Set B = Range("B1")

If Not A < B Then
    MsgBox "A is not greater than B."
Else
    MsgBox "B is not greater than A."
End If
   
End Sub

In the above code, you have used the NOT operator to test whether B is not greater than the A.

If you look at the condition statement, you can understand the actual condition to test is if B is greater than A, but as we have used the NOT statement, it will return FALSE if the condition is TRUE.

Here’s another example that you can use to understand it.

Sub myMacro()

If Not ActiveSheet.Name = Sheets("Sheet1").Name Then
    Sheets("Sheet1").Activate
End If

End Sub

Now, in this code, you have used NOT with IF to see if the active sheet is Sheet1 or not, and if it is not, the line of code that we have specified will activate the Sheet1.

Skip to content

Excel Logo

Excel If Cell Contains Text

Excel If Cell Contains Text Then

Excel If Cell Contains Text Then Formula helps you to return the output when a cell have any text or a specific text. You can check if a cell contains a some string or text  and produce something in other cell. For Example you can check if a cell A1 contains text ‘example text’  and print Yes or No in Cell B1. Following are the example Formulas to check if Cell contains text then return some thing in a Cell.

If Cell Contains Text

Here are the Excel formulas to check if Cell contains specific text then return something. This will return if there is any string or any text in given Cell. We can use this simple approach to check if a cell contains text, specific text, string,  any text using Excel If formula. We can use equals to  operator(=) to compare the strings .

If Cell Contains Text Then TRUE

Following is the Excel formula to return True if a Cell contains Specif Text. You can check a cell if there is given string in the Cell and return True or False.

=IF(ISNUMBER(FIND(“How”,A1,1)),TRUE,FALSE)

The formula will return true if it found the match, returns False of no match found.

If Cell Contains Text Then TRUE

If Cell Contains Partial Text

We can return Text If Cell Contains Partial Text. We use formula or VBA to Check Partial Text in a Cell.

Find for Case Sensitive Match:

We can check if a Cell Contains Partial Text then return something using Excel Formula. Following is a simple example to find the partial text in a given Cell. We can use if your want to make the criteria case sensitive.

=IF(ISERROR(FIND($E$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text

  • Here, Find Function returns the finding position of the given string
  • Use Find function is Case Sensitive
  • IsError Function check if Find Function returns Error, that means, string not found

Search for Not Case Sensitive Match:

We can use Search function to check if Cell Contains Partial Text. Search function useful if you want to make the checking criteria Not Case Sensitive.

=IF(ISERROR(SEARCH($F$1,A2,1)),”Not Found”,”Found”)

If Cell Contains Partial Text Not Case Sensitive

If Range of Cells Contains Text

We can check for the strings in a range of cells. Here is the formula to find If Range of Cells Contains Text. We can use Count If Formula to check the excel if range of cells contains specific text and return Text.

=IF(COUNTIF(A2:A21, “*Region 1d*”)>0,”Range Contais Text”,”Text Not Found in the Given Range”)
  • CountIf function counts the number of cells with given criteria
  • We can use If function to return the required Text
  • Formula displays the Text ‘Range Contains Text” if match found
  • Returns “Text Not Found in the Given Range” if match not found in the specified range

If Cells Contains Text From List

Below formulas returns text If Cells Contains Text from given List. You can use based on your requirement.

VlookUp to Check If Cell Contains Text from a List:
We can use VlookUp function to match the text in the Given list of Cells. And return the corresponding values.

  • Check if a List Contains Text:
    =IF(ISERR(VLOOKUP(F1,A1:B21,2,FALSE)),”False:Not Contains”,”True: Text Found”)
  • Check if a List Contains Text and Return Corresponding Value:
    =VLOOKUP(F1,A1:B21,2,FALSE)
  • Check if a List Contains Partial Text and Return its Value:
    =VLOOKUP(“*”&F1&”*”,A1:B21,2,FALSE)

If Cell Contains Text Then Return a Value

We can return some value if cell contains some string. Here is the the the Excel formula to return a value if a Cell contains Text. You can check a cell if there is given string in the Cell and return some string or value in another column.

If Cell Contains Text Then Return a Value

=IF(ISNUMBER(SEARCH(“How”,A1,1)),”Found”,”Not Found”)

The formula will return true if it found the match, returns False of no match found. can

Excel if cell contains word then assign value

You can replace any word in the following formula to check if cell contains word then assign value.

=IFERROR(IF(SEARCH(“Word”,A2,1)>0,1,0),””)

Excel if cell contains word then assign value
Search function will check for a given word in the required cell and return it’s position. We can use If function to check if the value is greater than 0 and assign a given value (example: 1) in the cell. search function returns #Value if there is no match found in the cell, we can handle this using IFERROR function.

Count If Cell Contains Text

We can check If Cell Contains Text Then COUNT. Here is the Excel formula to Count if a Cell contains Text. You can count the number of cells containing specific text.

=COUNTIF($A$2:$A$7,”*”&D2&”*”)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then COUNT

Count If Cell Contains Partial Text

We can count the cells based on partial match criteria. The following Excel formula Counts if a Cell contains Partial Text.

=COUNTIF(A2:A21, “*Region 1*”)
  • We can use the CountIf Function to Count the Cells if they contains given String
  • Wild-card operators helps to make the CountIf to check for the Partial String
  • Put Your Text between two asterisk symbols (*YourText*) to make the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to make the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to make the criteria to find your text end of given Cell

If Cell contains text from list then return value

Here is the Excel Formula to check if cell contains text from list then return value. We can use COUNTIF and OR function to check the array of values in a Cell and return the given Value. Here is the formula to check the list in range D2:D5 and check in Cell A2 and return value in B2.

=IF(OR(COUNTIF(A2,”*”&$D$2:$D$5&”*”)), “Return Value”, “”)

Excel If cell contains text from list then return value

If Cell Contains Text Then SUM

Following is the Excel formula to Sum if a Cell contains Text. You can total the cell values if there is given string in the Cell. Here is the example to sum the column B values based on the values in another Column.

=SUMIF($A$2:$A$7,”*”&D2&”*”,$B$2:$B$7)

The formula will Sum the values in Column B if the cells of Column A contains the given text.

If Cell Contains Text Then SUM

Sum If Cell Contains Partial Text

Use SumIfs function to Sum the cells based on partial match criteria. The following Excel formula Sums the Values if a Cell contains Partial Text.

=SUMIFS(C2:C21,A2:A21, “*Region 1*”)
  • SUMIFS Function will Sum the Given Sum Range
  • We can specify the Criteria Range, and wild-card expression to check for the Partial text
  • Put Your Text between two asterisk symbols (*YourText*) to Sum the Cells if the criteria to find any where in the given Cell
  • Add Asterisk symbol at end of your text (YourText*) to Sum the Cells if the criteria to find your text beginning of given Cell
  • Place Asterisk symbol at beginning of your text (*YourText) to Sum the Cells if criteria to find your text end of given Cell

VBA to check if Cell Contains Text

Here is the VBA function to find If Cells Contains Text using Excel VBA Macros.

If Cell Contains Partial Text VBA

We can use VBA to check if Cell Contains Text and Return Value. Here is the simple VBA code match the partial text. Excel VBA if Cell contains partial text macros helps you to use in your procedures and functions.

Sub sbCkeckforPartialText()
MsgBox CheckIfCellContainsPartialText(Cells(2, 1), “Region 1”)
End Sub
Function CheckIfCellContainsPartialText(ByVal cell As Range, ByVal strText As String) As Boolean
If InStr(1, cell.Value, strText) > 0 Then CheckIfCellContainsPartialText = True
End Function
  • CheckIfCellContainsPartialText VBA Function returns true if Cell Contains Partial Text
  • inStr Function will return the Match Position in the given string

If Cell Contains Text Then VBA MsgBox

Here is the simple VBA code to display message box if cell contains text. We can use inStr Function to search for the given string. And show the required message to the user.

Sub sbVBAIfCellsContainsText()
If InStr(1, Cells(2, 1), “Region 3”) > 0 Then blnMatch = True
If blnMatch = True Then MsgBox “Cell Contains Text”
End Sub
  • inStr Function will return the Match Position in the given string
  • blnMatch is the Boolean variable becomes True when match string
  • You can display the message to the user if a Range Contains Text

Which function returns true if cell a1 contains text?

You can use the Excel If function and Find function to return TRUE if Cell A1 Contains Text. Here is the formula to return True.

=IF(ISNUMBER(FIND(“YourText”,A1,1)),TRUE,FALSE)

Which function returns true if cell a1 contains text value?

You can use the Excel If function with Find function to return TRUE if a Cell A1 Contains Text Value. Below is the formula to return True based on the text value.

=IF(ISNUMBER(FIND(“YourTextValue”,A1,1)),TRUE,FALSE)

Share This Story, Choose Your Platform!

7 Comments

  1. Meghana
    December 27, 2019 at 1:42 pm — Reply

    Hi Sir,Thank you for the great explanation, covers everything and helps use create formulas if cell contains text values.

    Many thanks! Meghana!!

  2. Max
    December 27, 2019 at 4:44 pm — Reply

    Perfect! Very Simple and Clear explanation. Thanks!!

  3. Mike Song
    August 29, 2022 at 2:45 pm — Reply

    I tried this exact formula and it did not work.

  4. Theresa A Harding
    October 18, 2022 at 9:51 pm — Reply
  5. Marko
    November 3, 2022 at 9:21 pm — Reply

    Hi

    Is possible to sum all WA11?

    (A1) WA11 4

    (A2) AdBlue 1, WA11 223

    (A3) AdBlue 3, WA11 32, shift 4

    … and everything is in one column.

    Thanks you very much for your help.

    Sincerely Marko

  6. Mike
    December 9, 2022 at 9:59 pm — Reply

    Thank you for the help. The formula =OR(COUNTIF(M40,”*”&Vendors&”*”)) will give “TRUE” when some part of M40 contains a vendor from “Vendors” list. But how do I get Excel to tell which vendor it found in the M40 cell?

    • PNRao
      December 18, 2022 at 6:05 am — Reply

      Please describe your question more elaborately.
      Thanks!

© Copyright 2012 – 2020 | Excelx.com | All Rights Reserved

Page load link

Понравилась статья? Поделить с друзьями:
  • Excel vba if not isnull
  • Excel vba if not isempty
  • Excel vba if not instr
  • Excel vba if not false
  • Excel vba if not end if