Excel vba if not instr

  • If you would like to post, please check out the MrExcel Message Board FAQ and register here. If you forgot your password, you can reset your password.

  • Thread starter

    ilcaa

  • Start date

    May 4, 2012

  • #1

I cant see what the issue is with this if Not statement, it continues the IF statement even though it shouldnt. right??

b = «Just Listed»

If Not InStr(1, b, «Listed», 1) Then
msgbox «Not New»
End If

Loop

What do {} around a formula in the formula bar mean?

{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.

  • #2

Try

Code:

If InStr(1, b, "Listed", 1) = 0 Then

  • #3

yes that worked!

is that just a bug with vba using NOT Instr(), or it shouldnt be used like that??

thanks!

  • #4

I don’t think that you can use Not like that in a test for a numeric result in VBA. Not works fine when the result of a test is True or False.

  • #5

try it with this

If InStr(1, b, «Listed», 1) = 0 Then

edit: DOH too slow

Threads
1,192,536
Messages
5,993,056
Members
440,469
Latest member
Quaichlek

In this Article

  • VBA If Statement
    • If Then
  • ElseIF – Multiple Conditions
  • Else
  • If-Else
  • Nested IFs
  • IF – Or, And, Xor, Not
    • If Or
    • If And
    • If Xor
    • If Not
  • If Comparisons
    • If – Boolean Function
    • Comparing Text
    • VBA If Like
  • If Loops
  • If Else Examples
    • Check if Cell is Empty
    • Check if Cell Contains Specific Text
    • Check if cell contains text
    • If Goto
    • Delete Row if Cell is Blank
    • If MessageBox Yes / No
  • VBA If, ElseIf, Else in Access VBA

VBA If Statement

vba else if statement

If Then

VBA If Statements allow you to test if expressions are TRUE or FALSE, running different code based on the results.

Let’s look at a simple example:

If Range("a2").Value > 0 Then Range("b2").Value = "Positive"

This tests if the value in Range A2 is greater than 0. If so, setting Range B2 equal to “Positive”

vba if then

Note: When testing conditions we will use the =, >, <, <>, <=, >= comparison operators. We will discuss them in more detail later in the article.

Here is the syntax for a simple one-line If statement:

If [test_expression] then [action]

To make it easier to read, you can use a Line Continuation character (underscore) to expand the If Statements to two lines (as we did in the above picture):

If [test_expression] then _
    [action]
If Range("a2").Value > 0 Then _
   Range("b2").Value = "Positive"

End If

The above “single-line” if statement works well when you are testing one condition. But as your IF Statements become more complicated with multiple conditions, you will need to add an “End If” to the end of the if statement:

If Range("a2").Value > 0 Then
  Range("b2").Value = "Positive"
End If

vba end if

Here the syntax is:

If [test_expression] then
  [action]
End If

The End If signifies the end of the if statement.

Now let’s add in an ElseIF:

ElseIF – Multiple Conditions

The ElseIf is added to an existing If statement. ElseIf tests if a condition is met ONLY if the previous conditions have not been met.

In the previous example we tested if a cell value is positive. Now we will also test if the cell value is negative with an ElseIf:

If Range("a2").Value > 0 Then
    Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
    Range("b2").Value = "Negative"
End If

vba elseif

You can use multiple ElseIfs to test for multiple conditions:

Sub If_Multiple_Conditions()

    If Range("a2").Value = "Cat" Then
        Range("b2").Value = "Meow"
    ElseIf Range("a2").Value = "Dog" Then
        Range("b2").Value = "Woof"
    ElseIf Range("a2").Value = "Duck" Then
        Range("b2").Value = "Quack"
    End If

End Sub

Now we will add an Else:

Else

The Else will run if no other previous conditions have been met.

We will finish our example by using an Else to indicate that if the cell value is not positive or negative, then it must be zero:

If Range("a2").Value > 0 Then
    Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
    Range("b2").Value = "Negative"
Else
    Range("b2").Value = "Zero"
End If

vba else

If-Else

The most common type of If statement is a simple If-Else:

Sub If_Else()
    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    Else
        Range("b2").Value = "Not Positive"
    End If
End Sub

vba if else

Nested IFs

You can also “nest” if statements inside of each other.

Sub Nested_Ifs()
    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    Else
        If Range("a2").Value < 0 Then
            Range("b2").Value = "Negative"
        Else
            Range("b2").Value = "Zero"
        End If
    End If
End Sub

nested ifs

VBA Coding Made Easy

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

automacro

Learn More

IF – Or, And, Xor, Not

Next we will discuss the logical operators: Or, And, Xor, Not.

If Or

The Or operator tests if at least one condition is met.

The following code will test if the value in Range A2 is less than 5,000 or greater than 10,000:

If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Then
    Range("b2").Value = "Out of Range"
End If

if or

You can include multiple Ors in one line:

If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Or Range("a2").Value = 9999 Then
    Range("b2").Value = "Out of Range"
End If

If you are going to use multiple Ors, it’s recommended to use a line continuation character to make your code easier to read:

If Range("a2").Value < 5000 Or _
   Range("a2").Value > 10000 Or _
   Range("a2").Value = 9999 Then

       Range("b2").Value = "Out of Range"
End If

vba multiple ors

If And

The And operator allows you to test if ALL conditions are met.

If Range("a2").Value >= 5000 And Range("a2").Value <= 10000 Then
    Range("b2").Value = "In Range"
End If

vba if and

VBA Programming | Code Generator does work for you!

If Xor

The Xor operator allows you to test if exactly one condition is met. If zero conditions are met Xor will return FALSE, If two or more conditions are met, Xor will also return false.

I’ve rarely seen Xor used in VBA programming.

If Not

The Not operator is used to convert FALSE to TRUE or TRUE To FALSE:

Sub IF_Not()
    MsgBox Not (True)
End Sub

vba if not

Notice that the Not operator requires parenthesis surrounding the expression to switch.

The Not operator can also be applied to If statements:

If Not (Range("a2").Value >= 5000 And Range("a2").Value <= 10000) Then
    Range("b2").Value = "Out of Range"
End If

if not

If Comparisons

When making comparisons, you will usually use one of the comparison operators:

Comparison Operator Explanation
= Equal to
<> Not Equal to
> Greater than
>= Greater than or Equal to
< Less than
<= Less than or Equal to

However, you can also use any expression or function that results in TRUE or FALSE

If – Boolean Function

When build expressions for If Statements, you can also use any function that generates TRUE or False.  VBA has a few of these functions:

Function Description
IsDate Returns TRUE if expression is a valid date
IsEmpty Check for blank cells or undefined variables
IsError Check for error values
IsNull Check for NULL Value
IsNumeric Check for numeric value

They can be called like this:

If IsEmpty(Range("A1").Value) Then MsgBox "Cell Empty"

Excel also has many additional functions that can be called using WorksheetFunction. Here’s an example of the Excel IsText Function:

If Application.WorksheetFunction.IsText(Range("a2").Value) Then _ 
   MsgBox "Cell is Text"

You can also create your own User Defined Functions (UDFs). Below we will create a simple Boolean function that returns TRUE. Then we will call that function in our If statement:

Sub If_Function()

If TrueFunction Then
    MsgBox "True"
End If

End Sub

Function TrueFunction() As Boolean
    TrueFunction = True
End Function

vba if boolean function

Comparing Text

You can also compare text similar to comparing numbers:

Msgbox "a" = "b"
Msgbox "a" = "a"

When comparing text, you must be mindful of the “Case” (upper or lower).  By default, VBA considers letters with different cases as non-matching.  In other words, “A” <> “a”.

If you’d like VBA to ignore case, you must add the Option Compare Text declaration to the top of your module:

Option Compare Text

After making that declaration “A” = “a”:

Option Compare Text

Sub If_Text()
   MsgBox "a" = "A"
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA If Like

The VBA Like Operator allows you to make inexact comparisons of text. Click the “Like Operator” link to learn more, but we will show a basic example below:

Dim strName as String
strName = "Mr. Charles"

If strName Like "Mr*" Then
    MsgBox "True"
Else
    MsgBox "False"
End If

Here we’re using an asterisk “*” wildcard. The * stands for any number of any characters.  So the above If statement will return TRUE.  The Like operator is an extremely powerful, but often under-used tool for dealing with text.

If Loops

VBA Loops allow you to repeat actions. Combining IF-ELSEs with Loops is a great way to quickly process many calculations.

Continuing with our Positive / Negative example, we will add a For Each Loop to loop through a range of cells:

Sub If_Loop()
Dim Cell as Range

  For Each Cell In Range("A2:A6")
    If Cell.Value > 0 Then
      Cell.Offset(0, 1).Value = "Positive"
    ElseIf Cell.Value < 0 Then
      Cell.Offset(0, 1).Value = "Negative"
    Else
      Cell.Offset(0, 1).Value = "Zero"
     End If
  Next Cell

End Sub

vba else if statement

If Else Examples

Now we will go over some more specific examples.

Check if Cell is Empty

This code will check if a cell is empty. If it’s empty it will ignore the cell. If it’s not empty it will output the cell value to the cell to the right:

Sub If_Cell_Empty()

If Range("a2").Value <> "" Then
    Range("b2").Value = Range("a2").Value
End If

End Sub

vba if cell empty do nothing

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Check if Cell Contains Specific Text

The Instr Function tests if a string of text is found in another string. Use it with an If statement to check if a cell contains specific text:

If Instr(Range("A2").value,"text") > 0 Then
  Msgbox "Text Found"
End If

Check if cell contains text

This code will test if a cell is text:

Sub If_Cell_Is_Text()

If Application.WorksheetFunction.IsText(Range("a2").Value) Then
    MsgBox "Cell is Text"
End If

End Sub

If Goto

You can use the result of an If statement to “Go to” another section of code.

Sub IfGoTo ()

    If IsError(Cell.value) Then
        Goto Skip
    End If

    'Some Code

Skip:
End Sub

Delete Row if Cell is Blank

Using Ifs and loops you can test if a cell is blank and if so delete the entire row.

Sub DeleteRowIfCellBlank()

Dim Cell As Range

For Each Cell In Range("A2:A10")
    If Cell.Value = "" Then Cell.EntireRow.Delete
Next Cell

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

If MessageBox Yes / No

With VBA Message Boxes you’re able to ask the user to select from several options. The Yes/No Message Box asks the user to select Yes or No.  You can add a Yes / No Message Box to a procedure to ask the user if they would like to continue running the procedure or not. You handle the user’s input using an If statement.

Here is the Yes/No Message Box in practice:

vba yes no msgbox

Sub MsgBoxVariable()

Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)

  If answer = vbYes Then
    MsgBox "Yes"
  Else
    MsgBox "No"
  End If

End Sub

VBA If, ElseIf, Else in Access VBA

The If, ElseIf and Else functions work exactly the same in Access VBA as in Excel VBA.

You can use an If statement to check if there are records in a Recordset.

vba yes no msgbox

 

Andyvier

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

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

if cells(1,1) like «а» then… — если ячейка а1 содержит «а», то…
А как будет «не содержит» на vba?

Изменено: Andyvier27.09.2014 02:13:26

 

vikttur

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

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

if Not(cells(1,1) like «а») then..

 

Andyvier

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

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

 

ikki

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

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

#4

27.09.2014 03:56:34

Цитата
Andyvier пишет: if cells(1,1) like «а» then… — если ячейка а1 содержит «а», то…

кто научил Вас плохому?
это не «содержит», а просто «равно», т.е. то же самое, что и if cells(1,1)=»а» then…
для «содержит» таки так: if cells(1,1) like «*а*» then…
ну и. соответственно, для «не содержит» аналогично:  if not cells(1,1) like «*а*» then…
скобки необязательны — приоритет like выше, чем not

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

vikttur

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

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

#5

27.09.2014 04:02:32

Цитата
кто научил Вас плохому?

Не я! Я пытался только о хорошем. Скобки — они же безвредны… :)

 

ikki

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

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

ну, если не вспоминать о лимите в 64к на модуль — то да, безвредны.  :D
скобки в данном случае

необязательны

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

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

JeyCi

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

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

#7

27.09.2014 09:44:30

Цитата
Andyvier пишет: А как будет «не содержит» на vba?

есть ещё такая проверка — для элементов массива… если вам где-нибудь пригодиться когда-нибудь

Код
If InStr(1, CStr(c(i, 1)), "a") <> 0 Then  'проверка на присутствие  "a" в  c(i, 1)
If InStr(1, CStr(b(i, 1)), "a") = 0 Then   'проверка на отсутствие  "a" в  b(i, 1)

не проверяла работает ли InStr для ячеек (т к нет от вас полного кода)… но при случае можете

поэкспериментировать

, доработать… может cell.value на место элемента массива поставить в этих строках, может ещё как… на всякий случай для вашего словарного запаса на всю жизнь   :)   … на элементах массива точно работает

Изменено: JeyCi27.09.2014 09:46:19

чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах)

 

The_Prist

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

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

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

#8

27.09.2014 16:29:27

InStr работает с любым текстом и если подставлять ячейку — будет получено значение по умолчанию — т.е. Value и именно в нем будет произведен поиск указанного символа.

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

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

Public Function Contains(ByVal toSearch As String, ByVal toFind As String) As Boolean
    Contains = (Instr(toSearch, toFind) <> 0)
End Function

Тогда вы могли бы сказать,

If Not Contains(LCase(Data.Cells(i, 4).Value), "flowserve") Then
    If CDate(Data.Cells(i, "h").Value) < Date Then _
        Data.Cells(i, "h").Font.Color = -16776961
End If

и это работает именно так, как вы хотели.

Также обратите внимание, что вам не нужно LCase что-нибудь. Используйте опцию сравнения текста Instr вместо.

Public Function Contains(ByVal toSearch As String, ByVal toFind As String) As Boolean
    Contains = (Instr(1, toSearch, toFind, vbTextCompare) <> 0)
End Function

If Not Contains(Data.Cells(i, 4).Value, "flowserve") Then
    If CDate(Data.Cells(i, "h").Value) < Date Then _
        Data.Cells(i, "h").Font.Color = -16776961
End If

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

Simple Instr Function | Start Position | Zero | Instr and If | Case-insensitive Search

Use Instr in Excel VBA to find the position of a substring in a string. The Instr function is quite versatile.

Place a command button on your worksheet and add the code lines below. To execute the code lines, click the command button on the sheet.

Simple Instr Function

By default, the Instr function starts searching at the beginning of the string (position 1).

Code:

Dim state As String
state = «Virginia»

MsgBox InStr(state, «gin»)

Result:

Instr Result

Note: string «gin» found at position 4.

Start Position

The second Instr function below starts searching at position 7.

Code:

Dim state As String
state = «South Carolina»

MsgBox InStr(state, «o»)
MsgBox InStr(7, state, «o»)

Result:

Position 2

Position 10

Explanation: the first Instr function finds the string «o» at position 2. The second Instr function starts searching at position 7 and finds the string «o» at position 10.

Zero

The Instr function returns 0 if the string is not found (important as we will see next).

Code:

Dim state As String
state = «Florida»

MsgBox InStr(state, «us»)

Result:

Zero Result

Conclusion: string «us» not found.

Instr and If

Let’s create a simple VBA program that uses the Instr function.

Code:

Dim state As String, substring As String

state = Range(«A2»).Value
substring = Range(«B2»).Value

If InStr(state, substring) > 0 Then
    Range(«C2»).Value = «Found»
Else
    Range(«C2»).Value = «Not Found»
End If

Result when you click the command button on the sheet:

Instr and If

Explanation: string «outh» found at position 2. The Instr function returns 2. As a result, Excel VBA places the string «Found» into cell C2.

Case-insensitive Search

By default, the Instr function performs a case-sensitive search. Enter the string «dakota» into cell B2 and click the command button on the sheet.

Case-sensitive Search

Explanation: string «dakota» not found (first letter not capitalized). The Instr function returns 0. As a result, Excel VBA places the string «Not Found» into cell C2.

To perform a case-insensitive search, update the code as follows:

Dim state As String, substring As String

state = Range(«A2»).Value
substring = Range(«B2»).Value

If InStr(1, state, substring, vbTextCompare) > 0 Then
    Range(«C2»).Value = «Found»
Else
    Range(«C2»).Value = «Not Found»
End If

Result when you click the command button on the sheet:

Case-insensitive Search

Explanation: the Instr function shown above has 4 arguments. To perform a case-insensitive search, always specify a start position (first argument) and use vbTextCompare (fourth argument).

Понравилась статья? Поделить с друзьями:
  • Excel vba if not false
  • Excel vba if not end if
  • Excel vba if not dir
  • Excel vba if not date format
  • Excel vba if not boolean