Excel vba not contain

EXPLANATION

This tutorial shows how to test if a range does not contain a specific value and return a specified value if the formula tests true or false, by using an Excel formula and VBA.

This tutorial provides one Excel method that can be applied to test if a range does not contain a specific value and return a specified value by using an Excel IF and COUNTIF functions. In this example, if the Excel COUNTIF function returns a value of 0, meaning the range does not have cells with a value of 505, the test is TRUE and the formula will return a «Not in Range» value. Alternatively, if the Excel COUNTIF function returns a value of greater than 0, meaning the range has cells with a value of 505, the test is FALSE and the formula will return a «In Range» value.

This tutorial provides one VBA method that can be applied to test if a range does not contain a specific value and return a specified value and return a specified value.

FORMULA
=IF(COUNTIF(range, value)=0, value_if_true, value_if_false)

ARGUMENTS
range: The range of cells you want to count from.
value: he value that is used to determine which of the cells should be counted, from a specified range, if the cells’ value is equal to this value.
value_if_true: Value to be returned if the range does not contains the specific value.
value_if_false: Value to be returned if the range contains the specific value.

 

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 и именно в нем будет произведен поиск указанного символа.

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

This post will guide you how to delete rows if it does not contain a certain text value in Excel. How do I delete rows that do not contain specific text with VBA Macro in Excel. How to use Filter function to delete rows that do not contain a certain text in Excel.

  • Delete Rows That Do Not Contain Certain Text
  • Delete Rows That Do Not Contain Certain Text with VBA
  • Video: Delete Rows That Do Not Contain Certain Text

Table of Contents

  • Delete Rows That Do Not Contain Certain Text
    • Delete Rows That Do Not Contain Certain Text with VBA

Delete Rows That Do Not Contain Certain Text


If you want to delete rows that do not contain certain text in your selected range, you can use filter function to filter out that do not contain certain text, and then select all of the filtered rows, delete all of them. Just do the following steps:

#1 select one column which contain texts that you want to delete rows based on. (Assuming that you want to delete all rows that do not contain excel product name)

delete rows if do not contain certain text1

#2 go to DATA tab, click Filter command under Sort & Filter group. And one filter icon will be added into the first cell of the selected column.

delete rows if do not contain certain text2

#3 click Filter icon in the first cell, and checked all text filters except that certain text you want to contain in rows.

delete rows if do not contain certain text3

#4 all rows in which do not contain certain text value “excel” in Column A have been filtered out.

#5 select all of them except header row (the first row), and right click on it, and then select Delete Row from the drop down menu list.

delete rows if do not contain certain text4

#6 click Filter icon again, and select clear Filter From product. Click Ok button.

delete rows if do not contain certain text6

#7 all rows that do not contain certain text “excel” have been deleted.

delete rows if do not contain certain text7

Delete Rows That Do Not Contain Certain Text with VBA


You can also use an Excel VBA Macro to achieve the same result of deleting rows that do not contain certain text. Just do the following steps:

#1 open your excel workbook and then click on “Visual Basic” command under DEVELOPER Tab, or just press “ALT+F11” shortcut.

Get the position of the nth using excel vba1

#2 then the “Visual Basic Editor” window will appear.

#3 click “Insert” ->”Module” to create a new module.

convert column number to letter3

#4 paste the below VBA code into the code window. Then clicking “Save” button.

delete rows if do not contain certain text8

Sub DelRowsNotContainCertainText()
    Set myRange = Application.Selection
    Set myRange = Application.InputBox("Select one Range which contain texts that you want to delete rows based on", "DelRowsNotContainCertainText", myRange.Address, Type:=8)
    cText = Application.InputBox("Please type a certain text", "DelRowsNotContainCertainText", "", Type:=2)
    For i = myRange.Rows.Count To 1 Step -1
        Set myRow = myRange.Rows(i)
        Set myCell = myRow.Find(cText, LookIn:=xlValues)
        If myCell Is Nothing Then
           myRow.Delete
        End If
    Next
End Sub

#5 back to the current worksheet, then run the above excel macro. Click Run button.

delete rows if do not contain certain text9

#6 Select one Range which contain texts that you want to delete rows based on. click Ok button.

delete rows if do not contain certain text10

#7 Please type a certain text. click Ok button.

delete rows if do not contain certain text11

#8 let’s see the result:

delete rows if do not contain certain text12

Video: Delete Rows That Do Not Contain Certain Text

 

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

Bottom line: Learn how to apply text filters with VBA.  Includes examples for filtering for multiple items, begins with, contains, wildcards, etc.

Skill level: Intermediate

VBA AutoFilter Automate Text Filters

Download the File

The Excel file that contains the code can be downloaded below.  This file contains code for filtering different data types and filter types.  Please see my article on The Ultimate Guide to AutoFilters in VBA for more details.

Text Filters in Excel

When filtering a column that contains text, we can pick items from the filter drop-down menu list.

VBA AutoFilter Multiple Criteria from Filter Drop-down Menu Listbox

We can also use the Text Filters sub menu to create a custom filter.  This gives us options for filter criteria that equals, does not equal, begins with, ends with, contains, or does not contain specific text.  We can also use wildcard characters for these filters.

The following macro contains examples for different types of text filters.   It’s important to note that the Criteria parameter values are wrapped in quotation marks.  The comparison operators are also included inside the quotes.  Please see my post on The Ultimate Guide to Filters in VBA for more details on how to use the AutoFilter method and its parameters.

VBA Code Samples for Text Filters

The code in the box below can be copy/pasted into the VB Editor.

Sub AutoFilter_Text_Examples()
'Examples for filtering columns with TEXT

Dim lo As ListObject
Dim iCol As Long

  'Set reference to the first Table on the sheet
  Set lo = Sheet1.ListObjects(1)

  'Set filter field
  iCol = lo.ListColumns("Product").Index
  
  'Clear Filters
  lo.AutoFilter.ShowAllData
  
  'All lines starting with .AutoFilter are a continuation
  'of the with statement.
  With lo.Range
  
    'Single Item
    .AutoFilter Field:=iCol, Criteria1:="Product 2"
    
    '2 Criteria using Operator:=xlOr
    .AutoFilter Field:=iCol, _
                Criteria1:="Product 3", _
                Operator:=xlOr, _
                Criteria2:="Product 4"
    
    'More than 2 Criteria (list of items in an Array function)
    .AutoFilter Field:=iCol, _
                Criteria1:=Array("Product 4", "Product 5", "Product 6"), _
                Operator:=xlFilterValues
                        
    'Begins With - use asterisk as wildcard character at end of string
    .AutoFilter Field:=iCol, Criteria1:="Product*"
    
    'Ends With - use asterisk as wildcard character at beginning
    'of string
    .AutoFilter Field:=iCol, Criteria1:="*2"
    
    'Contains - wrap search text in asterisks
    .AutoFilter Field:=iCol, Criteria1:="*uct*"
    
    'Does not contain text
    'Start with Not operator <> and wrap search text in asterisks
    .AutoFilter Field:=iCol, Criteria1:="<>*8*"
    
    'Contains a wildcard character * or ?
    'Use a tilde ~ before the character to search for values with
    'wildcards
    .AutoFilter Field:=iCol, Criteria1:="Product 1~*"
  
  End With

End Sub

Filters & Data Types

The filter drop-down menu options change based on what type of data is in the column.   We have different filters for text, numbers, dates, and colors.  This creates A LOT of different combinations of Operators and Criteria for each type of filter.

I created separate posts for each of these filter types.  The posts contain explanations and VBA code examples.

  • How to Clear Filters with VBA
  • How to Filter for Blank & Non-Blank Cells
  • How to Filter for Numbers with VBA
  • How to Filter for Dates with VBA
  • How to Filter for Colors & Icons with VBA

The file in the downloads section above contains all of these code samples in one place.  You can add it to your Personal Macro Workbook and use the macros in your projects.

Please leave a comment below with any questions or suggestions.  Thanks! 🙂

Like this post? Please share to your friends:
  • Excel vba no messages
  • Excel vba interrupt execution
  • Excel vba no alerts
  • Excel vba integer or long
  • Excel vba next without for