Vba поиск символов в ячейке excel

Метод Find объекта Range для поиска ячейки по ее данным в VBA Excel. Синтаксис и компоненты. Знаки подстановки для поисковой фразы. Простые примеры.

Метод Find объекта Range предназначен для поиска ячейки и сведений о ней в заданном диапазоне по ее значению, формуле и примечанию. Чаще всего этот метод используется для поиска в таблице ячейки по слову, части слова или фразе, входящей в ее значение.

Синтаксис метода Range.Find

Expression.Find(What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)

Expression – это переменная или выражение, возвращающее объект Range, в котором будет осуществляться поиск.

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

Метод Range.Find возвращает объект Range, представляющий из себя первую ячейку, в которой найдена поисковая фраза (параметр What). Если совпадение не найдено, возвращается значение Nothing.

Если необходимо найти следующие ячейки, содержащие поисковую фразу, используется метод Range.FindNext.

Параметры метода Range.Find

Наименование Описание
Обязательный параметр
What Данные для поиска, которые могут быть представлены строкой или другим типом данных Excel. Тип данных параметра — Variant.
Необязательные параметры
After Ячейка, после которой следует начать поиск.
LookIn Уточняет область поиска. Список констант xlFindLookIn:

  • xlValues (-4163) – значения;
  • xlComments (-4144) – примечания*;
  • xlNotes (-4144) – примечания*;
  • xlFormulas (-4123) – формулы.
LookAt Поиск частичного или полного совпадения. Список констант xlLookAt:

  • xlWhole (1) – полное совпадение;
  • xlPart (2) – частичное совпадение.
SearchOrder Определяет способ поиска. Список констант xlSearchOrder:

  • xlByRows (1) – поиск по строкам;
  • xlByColumns (2) – поиск по столбцам.
SearchDirection Определяет направление поиска. Список констант xlSearchDirection:

  • xlNext (1) – поиск вперед;
  • xlPrevious (2) – поиск назад.
MatchCase Определяет учет регистра:

  • False (0) – поиск без учета регистра (по умолчанию);
  • True (1) – поиск с учетом регистра.
MatchByte Условия поиска при использовании двухбайтовых кодировок:

  • False (0) – двухбайтовый символ может соответствовать однобайтовому символу;
  • True (1) – двухбайтовый символ должен соответствовать только двухбайтовому символу.
SearchFormat Формат поиска – используется вместе со свойством Application.FindFormat.

* Примечания имеют две константы с одним значением. Проверяется очень просто: MsgBox xlComments и MsgBox xlNotes.

В справке Microsoft тип данных всех параметров, кроме SearchDirection, указан как Variant.

Знаки подстановки для поисковой фразы

Условные знаки в шаблоне поисковой фразы:

  • ? – знак вопроса обозначает любой отдельный символ;
  • * – звездочка обозначает любое количество любых символов, в том числе ноль символов;
  • ~ – тильда ставится перед ?, * и ~, чтобы они обозначали сами себя (например, чтобы тильда в шаблоне обозначала сама себя, записать ее нужно дважды: ~~).

Простые примеры

При использовании метода Range.Find в VBA Excel необходимо учитывать следующие нюансы:

  1. Так как этот метод возвращает объект Range (в виде одной ячейки), присвоить его можно только объектной переменной, объявленной как Variant, Object или Range, при помощи оператора Set.
  2. Если поисковая фраза в заданном диапазоне найдена не будет, метод Range.Find возвратит значение Nothing. Обращение к свойствам несуществующей ячейки будет генерировать ошибки. Поэтому, перед использованием результатов поиска, необходимо проверить объектную переменную на содержание в ней значения Nothing.

В примерах используются переменные:

  • myPhrase – переменная для записи поисковой фразы;
  • myCell – переменная, которой присваивается первая найденная ячейка, содержащая поисковую фразу, или значение Nothing, если поисковая фраза не найдена.

Пример 1

Sub primer1()

Dim myPhrase As Variant, myCell As Range

myPhrase = «стакан»

Set myCell = Range(«A1:L30»).Find(myPhrase)

If Not myCell Is Nothing Then

MsgBox «Значение найденной ячейки: « & myCell

MsgBox «Строка найденной ячейки: « & myCell.Row

MsgBox «Столбец найденной ячейки: « & myCell.Column

MsgBox «Адрес найденной ячейки: « & myCell.Address

Else

MsgBox «Искомая фраза не найдена»

End If

End Sub

В этом примере мы присваиваем переменной myPhrase значение для поиска – "стакан". Затем проводим поиск этой фразы в диапазоне "A1:L30" с присвоением результата поиска переменной myCell. Далее проверяем переменную myCell, не содержит ли она значение Nothing, и выводим соответствующие сообщения.

Ознакомьтесь с работой кода VBA в случаях, когда в диапазоне "A1:L30" есть ячейка со строкой, содержащей подстроку "стакан", и когда такой ячейки нет.

Пример 2

Теперь посмотрим, как метод Range.Find отреагирует на поиск числа. В качестве диапазона поиска будем использовать первую строку активного листа Excel.

Sub primer2()

Dim myPhrase As Variant, myCell As Range

myPhrase = 526.15

Set myCell = Rows(1).Find(myPhrase)

If Not myCell Is Nothing Then

MsgBox «Значение найденной ячейки: « & myCell

Else: MsgBox «Искомая фраза не найдена»

End If

End Sub

Несмотря на то, что мы присвоили переменной числовое значение, метод Range.Find найдет ячейку со значением и 526,15, и 129526,15, и 526,15254. То есть, как и в предыдущем примере, поиск идет по подстроке.

Чтобы найти ячейку с точным соответствием значения поисковой фразе, используйте константу xlWhole параметра LookAt:

Set myCell = Rows(1).Find(myPhrase, , , xlWhole)

Аналогично используются и другие необязательные параметры. Количество «лишних» запятых перед необязательным параметром должно соответствовать количеству пропущенных компонентов, предусмотренных синтаксисом метода Range.Find, кроме случаев указания необязательного параметра по имени, например: LookIn:=xlValues. Тогда используется одна запятая, независимо от того, сколько компонентов пропущено.

Пример 3

Допустим, у нас есть многострочная база данных в Excel. В первой колонке находятся даты. Нам необходимо создать отчет за какой-то период. Найти номер начальной строки для обработки можно с помощью следующего кода:

Sub primer3()

Dim myPhrase As Variant, myCell As Range

myPhrase = «01.02.2019»

myPhrase = CDate(myPhrase)

Set myCell = Range(«A:A»).Find(myPhrase)

If Not myCell Is Nothing Then

MsgBox «Номер начальной строки: « & myCell.Row

Else: MsgBox «Даты « & myPhrase & » в таблице нет»

End If

End Sub

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

Sub FindSymbol()
Dim aData(), aSpl
Dim lRw As Long, i As Long, k As Long, j As Long
    With Worksheets("sheet1") ' лист с исходными данными'
        lRw = .Cells(.Rows.Count, 1).End(xlUp).Row 'последняя строка с данными в столбце А'
        aData = .Range("A1:A" & lRw).Value ' тексты заносим в массив'
    End With

    ' определяем (с запасом) размерность массива результата'
    ReDim aRes(1 To lRw * 5, 1 To 1) ' 5 - макс к-во фрагментов в текстах'

    For i = 2 To lRw ' цикл по текстам, начиная со стоки 2'
        aSpl = Split(aData(i, 1), "#")  ' расщепляем на фрагменты'

        For j = 0 To UBound(aSpl)
            k = k + 1: aRes(k, 1) = aSpl(j)  ' записываем фрагменты в массив результата'
        Next j
    Next i

    With Worksheets("sheet1") ' лист для выгрузки'
        .Columns(3).ClearContents ' чистим столбец С'
        .Range("C2").Resize(k, 1).Value = aRes ' выгружаем результат в столбец С'
    End With

    MsgBox "OK", 64, "" ' радуемся :)'
End Sub

Для выгрузки в исходный диапазон вместо последнего блока With/End With записать строку

Worksheets("sheet1").Range("A2").Resize(k, 1).Value = aRes ' выгружаем результат в столбец A'

Можно формулой.

  • Для одной ячейки, результат по строкам:

    =СЖПРОБЕЛЫ(ПСТР(ПОДСТАВИТЬ(«#»&$A$2;»#»;ПОВТОР(» «;99));СТРОКА(A1)*99;99))

  • Для диапазона ячеек, результат по столбцам:

    =СЖПРОБЕЛЫ(ПСТР(ПОДСТАВИТЬ(«#»&$A2;»#»;ПОВТОР(» «;99));СТОЛБЕЦ(A1)*99;99))

Хотя для разнесения по столбцам можно проще — применить инструмент

Данные-Текст_по_столбцам-С_разделителем

  • Для диапазона ячеек, результат по строкам.

В доп. столбце находим количество фрагментов для подсказки основной формуле: в первой строке диапазона — 1, ниже формула

=ДЛСТР(A2)-ДЛСТР(ПОДСТАВИТЬ(A2;"#";))+1+B2

Результат:

=СЖПРОБЕЛЫ(ПСТР(ПОДСТАВИТЬ("#"&ИНДЕКС($A$2:$A$20;ПОИСКПОЗ(СТРОКА(A1);$B$2:$B$20));"#";ПОВТОР(" ";99));(СТРОКА(A1)-ИНДЕКС($B$2:$B$20;ПОИСКПОЗ(СТРОКА(A1);$B$2:$B$20))+1)*99;99))

введите сюда описание изображения

You will find everything you need to know on the Excel VBA Find function. The Range Find function allows you to find cells within your Excel worksheet (and workbook) that contain a certain text or value. In this post let us explore the many ways in which you can use the Find function.

Looking to search text within VBA strings instead? See the VBA InStr and VBA InStrRev functions

Before we show how to use VBA to search for text within an Excel spreadsheet let us first see how to do it Excel and explore the usually unknown features of the famous CTRL+F combo. See below where you can find it within the Home ribbon and Editing group.Excel Search feature CTRL+F
By clicking the above or simply using the key combo CTRL+F we can enter the Find & Replace modal window.
Excel Find and Replace example
As you notice above Excel easily finds 10 matches for the cells on the left. However there are several more interesting search combinations you can use, including usage of wildcards you can use to get more specific patterns. See some examples below:

Find Matches
some*text
  • some*text
  • some other text
some ?
  • some text
  • some other text
some*e*a
  • somedeal

As you might have already noticed I used 2 types of wildcards above:

  • * – the asterisk symbol represents zero or many of any type of characters. It can be injected between characters to replace either no or any number of characters.
  • ? – the question mark represents at least 1 character.

Now that we have a hand of the basic features of Excel in terms of word search let us move to how to use Excel VBA to find cells containing specific text.

VBA Range Find function

The VBA Find function is in fact a function of the Excel VBA Range object class. See Microsoft documentation for more details. A VBA Range represents any subset of cells within a spreadsheet – it can be a single cell, entire row or a patchwork of different cells and other Ranges. Executing the Find function in fact limits the search to only the cells within its Range object.

Below is the definition of the VBA Range Find function and its parameters:

.Find(What, [After] [LookIn], [LookAt], [SearchOrder], 
     [SearchDirection], [MatchCase], [MatchByte], [SearchFormat])

The Find function returns only the first match within the Range. To search for next items you need to follow it up with the FindNext function.

Parameter Required Description
What Required The value you are searching for
After Optional The cell range from which you start your search from
LookIn Optional What to search in e.g. Formulas, Values or Comments – constants of XlFindLookIn: xlValues, xlFormulas, xlComments, xlCommentsThreaded
LookAt Optional Whether to search in a part of the string in a cell or whether it needs to match the entire cell string – constants of XlLookAt: xlWhole, xlPart
SearchOrder Optional The sequence of the search i.e. whether to search by rows or columns – constants of XlSearchOrder: xlByRows or xlByColumns
SearchDirection Optional Whether to search forward (next) or backwards (previous) – constants of XlSearchDirection: xlNext, xlPrevious
MatchCase Optional Case sensitive or not – True or False
MatchByte Optional Used for double byte languages. True to have double-byte characters match only double-byte characters – True or False
SearchFormat Optional Allow searching by format. See Application.FindFormat – True or False

VBA Find – simple example

We will start with a very simple VBA Range Find function example – searching for a single cell within the entire Excel active spreadsheet:

Dim ws As Worksheet
Set ws = ActiveSheet

Debug.Print ws.Cells.Find("some")

Output:

some text

As you can see it found the first match within the Activesheet (currently open and top spreadsheet) and returned the found value.

VBA Find All

Finding all matches is a little more complicated in VBA than in Excel. We will need to use Do While loop to run via all matches:

Dim searchRange As Range, found As Range, firstFind As Range
    
'Set the search range to the entire worksheet
Set searchRange = ActiveSheet.Cells
    
'Search for the first match
Set found = searchRange.Find("some")
'Save the first found cell to check later whether we have completed the search
Set firstFind = found
    
'Loop through all items using FindNext Range function
Do
   If Not (found Is Nothing) Then
      Debug.Print found.Value
      Set found = searchRange.FindNext(found)
   End If
Loop While Not (found = firstFind)

Output:

some text
some other text
someone
something
somedeal
someones
somerset
someway
somewhat
somewhen

I highlighted above 2 key functions that were used the Range Find Function and the Range FindNext Function. As I mentioned above the Find function will only return the first match. To get next matches you need to run FindNext on the original range. This is I am executing FindNext on the searchRange variable and not the found variable.

Another interesting point to notice is the Do While…loop. Notice I am comparing the found variable to the firstFind variable. This is because when running FindNext it will at some point move to the first match once again and thus never end… it will just keep going in a cirle! Thus the loop is set to end once the FindNext function returns the same first cell.

Find using Wildcards

As mentioned above you can use 2 types of wildcards the asterisk * (zero or more characters) and the question mark ? (at least 1 character) to match slightly more complicates cases.

Dim ws As Worksheet
Set ws = ActiveSheet
   
Debug.Print ws.Cells.Find("some ?")
'Output: some text

Debug.Print ws.Cells.Find("some*w")
'Output: someway

VBA Find with After

To remind the After parameter of the Excel VBA Range Find function defines where you will start your search. It is useful when you don’t want to redefine your range just for the purpose of the search activity. See the example below:

Debug.Print Range("B2:B5").Find("some ?", After:=Range("B3"))

Output:

someone

As you can see below the Find function starts searching for the “some” string just after cell B3 i.e. it will start at B4 where it finds the first matching string.
VBA Find using After parameter

Find After – avoid wrap around

Even if we specify that the VBA Range Find function should start searching for the string after a specified cell, it might wrap around back to the beginning of the Range we specified if it does not find a match when going down. See example below to understand:

Debug.Print Range("B2:B5").Find("some*text", After:=Range("B3"))

Output:

some text

VBA Find using After - wrapping
As you see the search started at B4 however once the search pattern “some*text” was not found until B5 the function resumed search on the remaining cells B2:B3 to find “some text”.

Find After Avoid wrapping using VBA Find

What to do to avoid this wrapping? We can check whether the found text is not within the preceding range using the Application.Intersect function.

If the found cell is before our After cell then we can handle it as such:

 
Set found = Range("B2:B5").Find("some*text", After:=Range("B3"))

If Intersect(Range("B2:B3"), found) Is Nothing Then
    Debug.Print "Found text: " & found.Value
Else
    Debug.Print "Text found is within excluded range"
End If

Output:

Text found is within excluded range

However if the found cell is only After the cell we specified then it will show like this:

 
Set found = Range("B2:B5").Find("some", After:=Range("B3"))

If Intersect(Range("B2:B3"), found) Is Nothing Then
    Debug.Print "Found text: " & found.Value
Else
    Debug.Print "Text found is within excluded range"
End If

Output:

Found text: someone

Find in Values, Formulas, Comments

The VBA Range Find function allows you not only to search within Values (the evalution of your Excel formulas). It can also search instead (or including) within Formulas, Comments and even Excel Threaded Comments.

Let us explore how to use the LookIn parameter to look into specific attributes of a cell.
VBA Range Find using LookIn to search in Values, Formulas, Notes or Threaded Comments
In the code below we will search for the word dog within Values, Formulas, Notes and Threaded Comments (just the first one). We will return the address first. Notice that for Formulas the result was the same – this is because the Value and Formula is the same in this case.

    
Debug.Print Range("A1:D4").Find("dog", LookIn:=xlValues).AddressLocal
'Output: $A$2

Debug.Print Range("A1:D4").Find("dog", LookIn:=xlFormulas).AddressLocal
'Output: $A$2 - as the formula and value for "dog" are the same in this case
Debug.Print Range("A1:D4").Find("This is a dog", LookIn:=xlFormulas).AddressLocal
'Output: $B$2

Debug.Print Range("A1:D4").Find("dog", LookIn:=xlNotes).AddressLocal
'Output: $C$2

Debug.Print Range("A1:D4").Find("dog", LookIn:=xlCommentsThreaded).AddressLocal
'Output: $D$2

The same code but this time returning the actual Value, Formula, Note or Comment:

    
Debug.Print Range("A1:D4").Find("dog", LookIn:=xlValues).Value
'Output: dog

Debug.Print Range("A1:D4").Find("dog", LookIn:=xlFormulas).Formula2Local
'Output: dog
Debug.Print Range("A1:D4").Find("This is a dog", LookIn:=xlFormulas).Formula2Local
'Output: =IF(A2="Dog", "This is a Dog","Other")

Debug.Print Range("A1:D4").Find("dog", LookIn:=xlNotes).NoteText
'Output: This is a note about a dog

Debug.Print Range("A1:D4").Find("dog", LookIn:=xlCommentsThreaded).CommentThreaded.Text
'Output: This is a threaded comment about a dog

Find After – avoid wrap around

Complex patterns for Find

In some cases the pattern you want to find might be more complicated such as e.g. looking for cells with any sequence of numbers, emails, addresses, phone numbers etc. In this case the VBA Range Find function will be too limited. However, there is a solution with the help of so call VBA Regular Expressions. Regular Expressions help define almost any search pattern and are widely used in other programming languages.

If you want to learn more read my VBA Regex Tutorial otherwise a very simple example below.
Find complex text patterns with regular expressions
In below code snippet we would like to find only phone numbers – so we will create a simple expression that finds any sequence of digits.

    
'Define the Regular Expression
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
 
With regex
  'We will look only for sequences of at least 1 digit
  .Pattern = "[0-9]+"
End With
 

'Search in all cells within the Range
Dim r As Range
For Each r In Range("A1:D4")
    If regex.Test(r.Value) Then
        Debug.Print "Found a match: " & r.AddressLocal
    End If
Next r
Found a match: $A$3
title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Range.Find method (Excel)

vbaxl10.chm144128

vbaxl10.chm144128

excel

Excel.Range.Find

d9585265-8164-cb4d-a9e3-262f6e06b6b8

08/14/2019

high

Range.Find method (Excel)

Finds specific information in a range.

[!includeAdd-ins note]

Syntax

expression.Find (What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)

expression A variable that represents a Range object.

Parameters

Name Required/Optional Data type Description
What Required Variant The data to search for. Can be a string or any Microsoft Excel data type.
After Optional Variant The cell after which you want the search to begin. This corresponds to the position of the active cell when a search is done from the user interface.

Notice that After must be a single cell in the range. Remember that the search begins after this cell; the specified cell isn’t searched until the method wraps back around to this cell.

If you don’t specify this argument, the search starts after the cell in the upper-left corner of the range.

LookIn Optional Variant Can be one of the following XlFindLookIn constants: xlFormulas, xlValues, xlComments, or xlCommentsThreaded.
LookAt Optional Variant Can be one of the following XlLookAt constants: xlWhole or xlPart.
SearchOrder Optional Variant Can be one of the following XlSearchOrder constants: xlByRows or xlByColumns.
SearchDirection Optional Variant Can be one of the following XlSearchDirection constants: xlNext or xlPrevious.
MatchCase Optional Variant True to make the search case-sensitive. The default value is False.
MatchByte Optional Variant Used only if you have selected or installed double-byte language support. True to have double-byte characters match only double-byte characters. False to have double-byte characters match their single-byte equivalents.
SearchFormat Optional Variant The search format.

Return value

A Range object that represents the first cell where that information is found.

Remarks

This method returns Nothing if no match is found. The Find method does not affect the selection or the active cell.

The settings for LookIn, LookAt, SearchOrder, and MatchByte are saved each time you use this method. If you don’t specify values for these arguments the next time you call the method, the saved values are used. Setting these arguments changes the settings in the Find dialog box, and changing the settings in the Find dialog box changes the saved values that are used if you omit the arguments. To avoid problems, set these arguments explicitly each time you use this method.

Use the FindNext and FindPrevious methods to repeat the search.

When the search reaches the end of the specified search range, it wraps around to the beginning of the range. To stop a search when this wraparound occurs, save the address of the first found cell, and then test each successive found-cell address against this saved address.

To find cells that match more complicated patterns, use a For Each…Next statement with the Like operator. For example, the following code searches for all cells in the range A1:C5 that use a font whose name starts with the letters Cour. When Microsoft Excel finds a match, it changes the font to Times New Roman.

For Each c In [A1:C5] If c.Font.Name Like "Cour*" Then c.Font.Name = "Times New Roman" End If Next`

Examples

This example finds all cells in the range A1:A500 in worksheet one that contain the value 2, and changes the entire cell value to 5. That is, the values 1234 and 99299 both contain 2 and both cell values will become 5.

Sub FindValue()
    
    Dim c As Range
    Dim firstAddress As String

    With Worksheets(1).Range("A1:A500") 
        Set c = .Find(2, lookin:=xlValues) 
        If Not c Is Nothing Then 
            firstAddress = c.Address 
            Do 
                c.Value = 5 
                Set c = .FindNext(c) 
            Loop While Not c Is Nothing
        End If 
    End With
    
End Sub

This example finds all cells in the range A1:A500 on worksheet one that contain the substring «abc» and then replaces «abc» with «xyz».

Sub FindString()

    Dim c As Range
    Dim firstAddress As String

    With Worksheets(1).Range("A1:A500")
        Set c = .Find("abc", LookIn:=xlValues)
        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                c.Value = Replace(c.Value, "abc", "xyz")
                Set c = .FindNext(c)
            Loop While Not c Is Nothing
        End If
    End With

End Sub

[!includeSupport and feedback]

Поиск какого-либо значения в ячейках Excel довольно часто встречающаяся задача при программировании какого-либо макроса. Решить ее можно разными способами. Однако, в разных ситуациях использование того или иного способа может быть не оправданным. В данной статье я рассмотрю 2 наиболее распространенных способа.

Поиск перебором значений

Довольно простой в реализации способ. Например, найти в колонке «A» ячейку, содержащую «123» можно примерно так:

Sheets("Данные").Select
For y = 1 To Cells.SpecialCells(xlLastCell).Row
    If Cells(y, 1) = "123" Then
        Exit For
    End If
Next y
MsgBox "Нашел в строке: " + CStr(y)

Минусами этого так сказать «классического» способа являются: медленная работа и громоздкость. А плюсом является его гибкость, т.к. таким способом можно реализовать сколь угодно сложные варианты поиска с различными вычислениями и т.п.

Поиск функцией Find

Гораздо быстрее обычного перебора и при этом довольно гибкий. В простейшем случае, чтобы найти в колонке A ячейку, содержащую «123» достаточно такого кода:

Sheets("Данные").Select
Set fcell = Columns("A:A").Find("123")
If Not fcell Is Nothing Then
    MsgBox "Нашел в строке: " + CStr(fcell.Row)
End If

Вкратце опишу что делают строчки данного кода:
1-я строка: Выбираем в книге лист «Данные»;
2-я строка: Осуществляем поиск значения «123» в колонке «A», результат поиска будет в fcell;
3-я строка: Если удалось найти значение, то fcell будет содержать Range-объект, в противном случае — будет пустой, т.е. Nothing.

Полностью синтаксис оператора поиска выглядит так:

Find(What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)

What — Строка с текстом, который ищем или любой другой тип данных Excel

After — Ячейка, после которой начать поиск. Обратите внимание, что это должна быть именно единичная ячейка, а не диапазон. Поиск начинается после этой ячейки, а не с нее. Поиск в этой ячейке произойдет только когда весь диапазон будет просмотрен и поиск начнется с начала диапазона и до этой ячейки включительно.

LookIn — Тип искомых данных. Может принимать одно из значений: xlFormulas (формулы), xlValues (значения), или xlNotes (примечания).

LookAt — Одно из значений: xlWhole (полное совпадение) или xlPart (частичное совпадение).

SearchOrder — Одно из значений: xlByRows (просматривать по строкам) или xlByColumns (просматривать по столбцам)

SearchDirection — Одно из значений: xlNext (поиск вперед) или xlPrevious (поиск назад)

MatchCase — Одно из значений: True (поиск чувствительный к регистру) или False (поиск без учета регистра)

MatchByte — Применяется при использовании мультибайтных кодировок: True (найденный мультибайтный символ должен соответствовать только мультибайтному символу) или False (найденный мультибайтный символ может соответствовать однобайтному символу)

SearchFormat — Используется вместе с FindFormat. Сначала задается значение FindFormat (например, для поиска ячеек с курсивным шрифтом так: Application.FindFormat.Font.Italic = True), а потом при использовании метода Find указываем параметр SearchFormat = True. Если при поиске не нужно учитывать формат ячеек, то нужно указать SearchFormat = False.

Чтобы продолжить поиск, можно использовать FindNext (искать «далее») или FindPrevious (искать «назад»).

Примеры поиска функцией Find

Пример 1: Найти в диапазоне «A1:A50» все ячейки с текстом «asd» и поменять их все на «qwe»

With Worksheets(1).Range("A1:A50")
  Set c = .Find("asd", LookIn:=xlValues)
  Do While Not c Is Nothing
    c.Value = "qwe"
    Set c = .FindNext(c)
  Loop
End With

Обратите внимание: Когда поиск достигнет конца диапазона, функция продолжит искать с начала диапазона. Таким образом, если значение найденной ячейки не менять, то приведенный выше пример зациклится в бесконечном цикле. Поэтому, чтобы этого избежать (зацикливания), можно сделать следующим образом:

Пример 2: Правильный поиск значения с использованием FindNext, не приводящий к зацикливанию.

With Worksheets(1).Range("A1:A50")
  Set c = .Find("asd", lookin:=xlValues)
  If Not c Is Nothing Then
    firstResult = c.Address
    Do
      c.Font.Bold = True
      Set c = .FindNext(c)
      If c Is Nothing Then Exit Do
    Loop While c.Address <> firstResult
  End If
End With

В ниже следующем примере используется другой вариант продолжения поиска — с помощью той же функции Find с параметром After. Когда найдена очередная ячейка, следующий поиск будет осуществляться уже после нее. Однако, как и с FindNext, когда будет достигнут конец диапазона, Find продолжит поиск с его начала, поэтому, чтобы не произошло зацикливания, необходимо проверять совпадение с первым результатом поиска.

Пример 3: Продолжение поиска с использованием Find с параметром After.

With Worksheets(1).Range("A1:A50")
  Set c = .Find("asd", lookin:=xlValues)
  If Not c Is Nothing Then
    firstResult = c.Address
    Do
      c.Font.Bold = True
      Set c = .Find("asd", After:=c, lookin:=xlValues)
      If c Is Nothing Then Exit Do
    Loop While c.Address <> firstResult
  End If
End With

Следующий пример демонстрирует применение SearchFormat для поиска по формату ячейки. Для указания формата необходимо задать свойство FindFormat.

Пример 4: Найти все ячейки с шрифтом «курсив» и поменять их формат на обычный (не «курсив»)

lLastRow = Cells.SpecialCells(xlLastCell).Row
lLastCol = Cells.SpecialCells(xlLastCell).Column
Application.FindFormat.Font.Italic = True
With Worksheets(1).Range(Cells(1, 1), Cells(lLastRow, lLastCol))
  Set c = .Find("", SearchFormat:=True)
  Do While Not c Is Nothing
    c.Font.Italic = False
    Set c = .Find("", After:=c, SearchFormat:=True)
  Loop
End With

Примечание: В данном примере намеренно не используется FindNext для поиска следующей ячейки, т.к. он не учитывает формат (статья об этом: https://support.microsoft.com/ru-ru/kb/282151)

Коротко опишу алгоритм поиска Примера 4. Первые две строки определяют последнюю строку (lLastRow) на листе и последний столбец (lLastCol). 3-я строка задает формат поиска, в данном случае, будем искать ячейки с шрифтом Italic. 4-я строка определяет область ячеек с которой будет работать программа (с ячейки A1 и до последней строки и последнего столбца). 5-я строка осуществляет поиск с использованием SearchFormat. 6-я строка — цикл пока результат поиска не будет пустым. 7-я строка — меняем шрифт на обычный (не курсив), 8-я строка продолжаем поиск после найденной ячейки.

Хочу обратить внимание на то, что в этом примере я не стал использовать «защиту от зацикливания», как в Примерах 2 и 3, т.к. шрифт меняется и после «прохождения» по всем ячейкам, больше не останется ни одной ячейки с курсивом.

Свойство FindFormat можно задавать разными способами, например, так:

With Application.FindFormat.Font 
  .Name = "Arial" 
  .FontStyle = "Regular" 
  .Size = 10 
End With

Поиск последней заполненной ячейки с помощью Find

Следующий пример — применение функции Find для поиска последней ячейки с заполненными данными. Использованные в Примере 4 SpecialCells находит последнюю ячейку даже если она не содержит ничего, но отформатирована или в ней раньше были данные, но были удалены.

Пример 5: Найти последнюю колонку и столбец, заполненные данными

Set c = Worksheets(1).UsedRange.Find("*", SearchDirection:=xlPrevious)
If Not c Is Nothing Then
  lLastRow = c.Row: lLastCol = c.Column 
Else
  lLastRow = 1: lLastCol = 1
End If
MsgBox "lLastRow=" & lLastRow & " lLastCol=" & lLastCol

В этом примере используется UsedRange, который так же как и SpecialCells возвращает все используемые ячейки, в т.ч. и те, что были использованы ранее, а сейчас пустые. Функция Find ищет ячейку с любым значением с конца диапазона.

Поиск по шаблону (маске)

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

Пример 6: Выделить красным шрифтом ячейки, в которых текст начинается со слова из 4-х букв, первая и последняя буквы «т», при этом после этого слова может следовать любой текст.

With Worksheets(1).Cells
  Set c = .Find("т??т*", LookIn:=xlValues, LookAt:=xlWhole)
  If Not c Is Nothing Then
    firstResult = c.Address
    Do
      c.Font.Color = RGB(255, 0, 0)
      Set c = .FindNext(c)
      If c Is Nothing Then Exit Do
    Loop While c.Address <> firstResult
  End If
End With

Для поиска функцией Find по маске (шаблону) можно применять символы:
* — для обозначения любого количества любых символов;
? — для обозначения одного любого символа;
~ — для обозначения символов *, ? и ~. (т.е. чтобы искать в тексте вопросительный знак, нужно написать ~?, чтобы искать именно звездочку (*), нужно написать ~* и наконец, чтобы найти в тексте тильду, необходимо написать ~~)

Поиск в скрытых строках и столбцах

Для поиска в скрытых ячейках нужно учитывать лишь один нюанс: поиск нужно осуществлять в формулах, а не в значениях, т.е. нужно использовать LookIn:=xlFormulas

Поиск даты с помощью Find

Если необходимо найти текущую дату или какую-то другую дату на листе Excel или в диапазоне с помощью Find, необходимо учитывать несколько нюансов:

  • Тип данных Date в VBA представляется в виде #[месяц]/[день]/[год]#, соответственно, если необходимо найти фиксированную дату, например, 01 марта 2018 года, необходимо искать #3/1/2018#, а не «01.03.2018»
  • В зависимости от формата ячеек, дата может выглядеть по-разному, поэтому, чтобы искать дату независимо от формата, поиск нужно делать не в значениях, а в формулах, т.е. использовать LookIn:=xlFormulas

Приведу несколько примеров поиска даты.

Пример 7: Найти текущую дату на листе независимо от формата отображения даты.

d = Date
Set c = Cells.Find(d, LookIn:=xlFormulas, LookAt:=xlWhole)
If Not c Is Nothing Then
  MsgBox "Нашел"
Else
  MsgBox "Не нашел"
End If

Пример 8: Найти 1 марта 2018 г.

d = #3/1/2018#
Set c = Cells.Find(d, LookIn:=xlFormulas, LookAt:=xlWhole)
If Not c Is Nothing Then
  MsgBox "Нашел"
Else
  MsgBox "Не нашел"
End If

Искать часть даты — сложнее. Например, чтобы найти все ячейки, где месяц «март», недостаточно искать «03» или «3». Не работает с датами так же и поиск по шаблону. Единственный вариант, который я нашел — это выбрать формат в котором месяц прописью для ячеек с датами и искать слово «март» в xlValues.

Тем не менее, можно найти, например, 1 марта независимо от года.

Пример 9: Найти 1 марта любого года.

d = #3/1/1900#
Set c = Cells.Find(Format(d, "m/d/"), LookIn:=xlFormulas, LookAt:=xlPart)
If Not c Is Nothing Then
  MsgBox "Нашел"
Else
  MsgBox "Не нашел"
End If

In this Article

  • VBA Find
  • Find VBA Example
  • VBA Find without Optional Parameters
    • Simple Find Example
    • Find Method Notes
    • Nothing Found
  • Find Parameters
    • After Parameter and Find Multiple Values
    • LookIn Parameter
    • Using the LookAt Parameter
    • SearchOrder Parameter
    • SearchDirection Parameter
    • MatchByte Parameter
    • SearchFormat Parameter
    • Using Multiple Parameters
  • Replace in Excel VBA
    • Replace Without Optional Parameters
  • Using VBA to Find or Replace Text Within a VBA Text String
    • INSTR – Start
    • VBA Replace Function

This tutorial will demonstrate how to use the Find and Replace methods in Excel VBA.

VBA Find

Excel has excellent built-in Find and Find & Replace tools.

They can be activated with the shortcuts CTRL + F (Find) or CTRL + H (Replace) or through the Ribbon: Home > Editing > Find & Select.

find excel vba

By clicking Options, you can see advanced search options:

advanced find vba

You can easily access these methods using VBA.

Find VBA Example

To demonstrate the Find functionality, we created the following data set in Sheet1.

PIC 02

If you’d like to follow along, enter the data into your own workbook.

VBA Find without Optional Parameters

When using the VBA Find method, there are many optional parameters that you can set.

We strongly recommend defining all parameters whenever using the Find Method!

If you don’t define the optional parameters, VBA will use the currently selected parameters in Excel’s Find window. This means, you may not know what search parameters are being used when the code is ran. Find could be ran on the entire workbook or a sheet. It could search for formulas or values. There’s no way to know, unless you manually check what’s currently selected in Excel’s Find Window.

For simplicity, we will start with an example with no optional parameters defined.

Simple Find Example

Let’s look at a simple Find example:

Sub TestFind()
Dim MyRange As Range

Set MyRange = Sheets("Sheet1").UsedRange.Find("employee")
MsgBox MyRange.Address
MsgBox MyRange.Column
MsgBox MyRange.Row

End Sub

This code searches for “employee” in the Used Range of Sheet1. If it finds “employee”, it will assign the first found range to range variable MyRange.

Next, Message Boxes will display with the address, column, and row of the found text.

In this example, the default Find settings are used (assuming they have not been changed in Excel’s Find Window):

  • The search text is partially matched to the cell value (an exact cell match is not required)
  • The search is not case sensitive.
  • Find only searches a single worksheet

These settings can be changed with various optional parameters (discussed below).

Find Method Notes

  • Find does not select the cell where the text is found.  It only identifies the found range, which you can manipulate in your code.
  • The Find method will only locate the first instance found.
  • You can use wildcards (*) e.g. search for ‘E*’

Nothing Found

If the search text does not exist, then the range object will remain empty. This causes a major problem when your code tries to display the location values because they do not exist.  This will result in an error message which you do not want.

Fortunately, you can test for an empty range object within VBA using the Is Operator:

If Not MyRange Is Nothing Then

Adding the code to our previous example:

Sub TestFind()
Dim MyRange As Range

Set MyRange = Sheets("Sheet1").UsedRange.Find("employee")
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
    MsgBox MyRange.Column
    MsgBox MyRange.Row
Else
    MsgBox "Not found"
End If
End Sub 

VBA Coding Made Easy

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

automacro

Learn More

Find Parameters

So far, we have only looked at a basic example of using the Find method.  However, there are a number of optional parameters available to help you refine your search

Parameter Type Description Values
What Required The value to search for Any data type such as a string or numeric
After Optional Single cell reference to begin your search Cell address
LookIn Optional Use Formulas, Values, Comments for search xlValues, xlFormulas, xlComments
LookAt Optional Match part or whole of a cell xlWhole, xlPart
SearchOrder Optional The Order to search in – rows or columns xlByRows, xlByColummns
SearchDirection Optional Direction for search to go in – forward or backward xlNext, xlPrevious
MatchCase Optional Search is case sensitive or not True or False
MatchByte Optional Used only if you have installed double byte language support e.g. Chinese language True or False
SearchFormat Optional Allow searching by format of cell True or False

After Parameter and Find Multiple Values

You use the After parameter to specify the starting cell for your search. This is useful where there is more than one instance of the value that you are searching for.

If a search has already found one value and you know that there will be more values found, then you use the Find method with the ‘After’ parameter to record the first instance and then use that cell as the starting point for the next search.

You can use this to find multiple instances of your search text:

Sub TestMultipleFinds()
Dim MyRange As Range, OldRange As Range, FindStr As String

'Look for first instance of "‘Light & Heat"
Set MyRange = Sheets("Sheet1").UsedRange.Find("Light & Heat")

'If not found then exit
If MyRange Is Nothing Then Exit Sub

'Display first address found
MsgBox MyRange.Address

'Make a copy of the range object
Set OldRange = MyRange

'Add the address to the string delimiting with a "|" character
FindStr = FindStr & "|" & MyRange.Address

'Iterate through the range looking for other instances
Do
    'Search for ‘Light & Heat’ using the previous found address as the After parameter   
    Set MyRange = Sheets("Sheet1").UsedRange.Find("Light & Heat", After:=Range(OldRange.Address))

    'If the address has already been found then exit the do loop – this stops continuous looping
    If InStr(FindStr, MyRange.Address) Then Exit Do
    
    'Display latest found address
    MsgBox MyRange.Address

    'Add the latest address to the string of addresses
    FindStr = FindStr & "|" & MyRange.Address

    'make a copy of the current range
     Set OldRange = MyRange
Loop
End Sub

This code will iterate through the used range, and will display the address every time it finds an instance of ‘Light & Heat’

Note that the code will keep looping until a duplicate address is found in FindStr, in which case it will exit the Do loop.

LookIn Parameter

You can use the LookIn parameter to specify which component of the cell you want to search in.  You can specify values, formulas, or comments in a cell.

  • xlValues – Searches cell values (the final value of a cell after it’s calculation)
  • xlFormulas – Searches within the cell formula itself (whatever is entered into the cell)
  • xlComments – Searches within cell notes
  • xlCommentsThreaded – Searches within cell comments

Assuming that a formula has been entered on the worksheet, you could use this example code to find the first location of any formula:

Sub TestLookIn()
Dim MyRange As Range

Set MyRange = Sheets("Sheet1").UsedRange.Find("=", LookIn:=xlFormulas)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address   
Else
    MsgBox "Not found"
 End If
End Sub

If the ‘LookIn’ parameter was set to xlValues, the code would display a ‘Not Found’ message. In this example it will return B10.

VBA Programming | Code Generator does work for you!

Using the LookAt Parameter

The LookAt parameter determines whether find will search for an exact cell match, or search for any cell containing the search value.

  • xlWhole – Requires the entire cell to match the search value
  • xlPart – Searches within a cell for the search string

This code example will locate the first cell containing the text “light”. With Lookat:=xlPart, it will return a match for “Light & Heat”.

Sub TestLookAt()
Dim MyRange As Range
Set MyRange = Sheets("Sheet1").UsedRange.Find("light", Lookat:=xlPart)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
  Else
    MsgBox "Not found"  
End If
End Sub

If xlWhole was set, a match would only return if the cell value was “light”.

SearchOrder Parameter

The SearchOrder parameter dictates how the search will be carried out throughout the range.

  • xlRows – Search is done row by row
  • xlColumns – Search is done column by column
Sub TestSearchOrder()
Dim MyRange As Range
Set MyRange = Sheets("Sheet1").UsedRange.Find("employee", SearchOrder:=xlColumns)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
Else
    MsgBox "Not found"
End If
End Sub

This influences which match will be found first.

Using the test data entered into the worksheet earlier, when the search order is columns, the located cell is A5.  When the search order parameter is changed to xlRows, the located cell is C4

This is important if you have duplicate values within the search range and you want to find the first instance under a particular column name.

SearchDirection Parameter

The SearchDirection parameter dictates which direction the search will go in – effectively forward or backwards.

  • xlNext – Search for next matching value in range
  • xlPrevious – Search for previous matching value in range

Again, if there are duplicate values within the search range, it can have an effect on which one is found first.

Sub TestSearchDirection()
Dim MyRange As Range

Set MyRange = Sheets("Sheet1").UsedRange.Find("heat", SearchDirection:=xlPrevious)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
Else
    MsgBox "Not found"
End If
End Sub

Using this code on the test data, a search direction of xlPrevious will return a location of C9.  Using the xlNext parameter will return a location of A4.

The Next parameter means that the search will begin in the top left-hand corner of the search range and work downwards. The Previous parameter means that the search will start in the bottom right-hand corner of the search range and work upwards.

MatchByte Parameter

The MatchBye parameter is only used for languages which use a double byte to represent each character, such as Chinese, Russian, and Japanese.

If this parameter is set to ‘True’ then Find will only match double-byte characters with double-byte characters.  If the parameter is set to ‘False’, then a double-byte character will match with single or double-byte characters.

SearchFormat Parameter

The SearchFormat parameter enables you to search for matching cell formats. This could be a particular font being used, or a bold font, or a text color.  Before you use this parameter, you must set the format required for the search using the Application.FindFormat property.

Here is an example of how to use it:

Sub TestSearchFormat()
Dim MyRange As Range

Application.FindFormat.Clear
Application.FindFormat.Font.Bold = True
Set MyRange = Sheets("Sheet1").UsedRange.Find("heat", Searchformat:=True)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
Else
    MsgBox "Not found"
End If
Application.FindFormat.Clear
End Sub

In this example, the FindFormat property is set to look for a bold font. The Find statement then searches for the word ‘heat’ setting the SearchFormat parameter to True so that it will only return an instance of that text if the font is bold.

In the sample worksheet data shown earlier, this will return A9, which is the only cell containing the word ‘heat’ in a bold font.

Make sure that the FindFormat property is cleared at the end of the code.  If you do not your next search will still take this into account and return incorrect results.

Where you use a SearchFormat parameter, you can also use a wildcard (*) as the search value.  In this case it will search for any value with a bold font:

Set MyRange = Sheets("Sheet1").UsedRange.Find("*", Searchformat:=True)

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

Using Multiple Parameters

All the search parameters discussed here can be used in combination with each other if required.

For example, you could combine the ‘LookIn’ parameter with the ‘MatchCase’ parameter so that you look at the whole of the cell text, but it is case-sensitive

Sub TestMultipleParameters()
Dim MyRange As Range
Set MyRange = Sheets("Sheet1").UsedRange.Find("Light & Heat", LookAt:=xlWhole, MatchCase:=True)
If Not MyRange Is Nothing Then
    MsgBox MyRange.Address
Else
    MsgBox "Not found"
End If
End Sub

In this example, the code will return A4, but if we only used a part of the text e.g. ‘heat’, nothing would be found because we are matching on the whole of the cell value.  Also, it would fail due to the case not matching.

Set MyRange = Sheets("Sheet1").UsedRange.Find("heat", LookAt:=xlWhole, MatchCase:=True)

Replace in Excel VBA

There is, as you may expect, a Replace function in Excel VBA, which works in a very similar way to ‘Find’ but replaces the values at the cell location found with a new value.

These are the parameters that you can use in a Replace method statement.  These operate in exactly the same way as for the Find method statement.  The only difference to ‘Find’ is that you need to specify a Replacement parameter.

Name Type Description Values
What Required The value to search for Any data type such as a string or numeric
Replacement Required The replacement string. Any data type such as a string or numeric
LookAt Optional Match part or the whole of a cell xlPart or xlWhole
SearchOrder Optional The order to search in – Rows or Columns xlByRows or xlByColumns
MatchCase Optional Search is case sensitive or not True or False
MatchByte Optional Used only if you have installed double byte language support True or False
SearchFormat Optional Allow searching by format of cell True or False
ReplaceFormat Optional The replace format for the method. True or False

The Replace Format parameter searches for a cell with a particular format e.g. bold in the same way the SearchFormat parameter operates in the Find method. You need to set the Application.FindFormat property first, as shown in the Find example code shown earlier 

Replace Without Optional Parameters

At its simplest, you only need to specify what you are searching for and what you want to replace it with.

Sub TestReplace()
Sheets("Sheet1").UsedRange.Replace What:="Light & Heat", Replacement:="L & H"
End Sub

Note that the Find method will only return the first instance of the matched value, whereas the Replace method works through the entire range specified and replaces everything that it finds a match on.

The replacement code shown here will replace every instance of ‘Light & Heat’ with ‘L & H’ through the entire range of cells defined by the UsedRange object

Using VBA to Find or Replace Text Within a VBA Text String

The above examples work great when using VBA to interact with Excel data. However, to interact with VBA strings, you can use built-in VBA Functions like INSTR and REPLACE.

You can use the INSTR Function to locate a string of text within a longer string.

Sub TestInstr()
MsgBox InStr("This is MyText string", "MyText")
End Sub

This example code will return the value of 9, which is the number position where ‘MyText’ is found in the string to be searched.

Note that it is case sensitive. If ‘MyText’ is all lower case, then a value of 0 will be returned which means that the search string was not found. Below we will discuss how to disable case-sensitivity.

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

INSTR – Start

There are two further optional parameters available.  You can specify the start point for the search:

MsgBox InStr(9, "This is MyText string", "MyText")

The start point is specified as 9 so it will still return 9.  If the start point was 10, then it would return 0 (no match) as the start point would be too far forward.

INSTR – Case Sensitivity

You can also set a Compare parameter to vbBinaryCompare or vbTextCompare. If you set this parameter, the statement must have a start parameter value.

  • vbBinaryCompare – Case-sensitive (Default)
  • vbTextCompare – Not Case-sensitive
MsgBox InStr(1, "This is MyText string", "mytext", vbTextCompare)

This statement will still return 9, even though the search text is in lower case.

To disable case-sensitivity you can also declare Option Compare Text at the top of your code module.

VBA Replace Function

If you wish to replace characters in a string with different text within your code, then the Replace method is ideal for this:

Sub TestReplace()
MsgBox Replace("This is MyText string", "MyText", "My Text")
End Sub

This code replaces ‘MyText’ with ‘My Text’.  Note that the search string is case sensitive as a binary compare is the default.

You can also add other optional parameters:

  • Start – defines position in the initial string that the replacement has to start from. Unlike in the Find method, it returns a truncated string starting from the character number defined by the Start parameter.
  • Count – defines the number of replacements to be made.  By default, Replace will change every instance of the search text found, but you can limit this to a single replacement by setting the Count parameter to 1
  • Compare – as in the Find method you can specify a binary search or a text search using vbBinaryCompare or vbTextCompare.  Binary is case sensitive and text is non case sensitive
MsgBox Replace("This is MyText string (mytext)", "MyText", "My Text", 9, 1, vbTextCompare)

This code returns ‘My Text string (mytext)’. This is because the start point given is 9, so the new returned string starts at character 9.   Only the first ‘MyText’ has been changed because the Count parameter is set to 1.

The Replace method is ideal for solving problems like peoples’ names containing apostrophes e.g. O’Flynn. If you are using single quotes to define a string value and there is an apostrophe, this will cause an error because the code will interpret the apostrophe as the end of the string and will not recognize the remainder of the string.

You can use the Replace method to replace the apostrophe with nothing, removing it completely.

Поиск символа в ячейке

agh1511

Дата: Четверг, 13.08.2020, 13:57 |
Сообщение № 1

Группа: Пользователи

Ранг: Прохожий

Сообщений: 7


Репутация:

0

±

Замечаний:
0% ±


Excel 2019

Добрый день!

Требуется помощь.
Есть столбец с данными (строк около 10000)
В столбце «O» есть числовые и текст типа 8568,88 и 8868.88
Необходимо выделить цветом все ячейки, где вместо запятой стоит точка именно в конкретном столбце «O»

Спасибо

 

Ответить

Nic70y

Дата: Четверг, 13.08.2020, 14:07 |
Сообщение № 2

Группа: Друзья

Ранг: Экселист

Сообщений: 8134


Репутация:

1999

±

Замечаний:
0% ±


Excel 2010

[vba]

Код

u = InStr(ячейка, «.») ‘поиск точки
If u > 0 Тhen ‘если нашли

[/vba]можно попробовать формулу в Условном форматировании

АпДэйт
а вообще зачем оно Вам надо?
выделили столбец,
нажали ctrl+h
найти: .
заменить на: ,
заменить все
и все — нет больше точек.


ЮMoney 41001841029809

Сообщение отредактировал Nic70yЧетверг, 13.08.2020, 16:25

 

Ответить

agh1511

Дата: Пятница, 14.08.2020, 09:19 |
Сообщение № 3

Группа: Пользователи

Ранг: Прохожий

Сообщений: 7


Репутация:

0

±

Замечаний:
0% ±


Excel 2019

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

 

Ответить

Ответить

agh1511

Дата: Пятница, 14.08.2020, 09:28 |
Сообщение № 5

Группа: Пользователи

Ранг: Прохожий

Сообщений: 7


Репутация:

0

±

Замечаний:
0% ±


Excel 2019

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

 

Ответить

The_Fog

0 / 0 / 2

Регистрация: 24.02.2016

Сообщений: 75

1

Поиска символов в ячейках и их замена

02.02.2017, 14:48. Показов 9604. Ответов 14

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Нужно найти определенное слово в ячейке и заменить без изменения остальных слов в этой ячейке.
Написал макрос:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Dim x As Range: Application.ScreenUpdating = False
 Dim flag As Integer
 
    For Each x In Range("E2:E150")
    flag = 0
  
    If x.Value = "11" And flag = 0 Then
       x.Replace "11", "22"
       flag = 1
       End If
       
    If x.Value = "22" And flag = 0 Then
       x.Replace "22", "11"
    End If
    
     
    Next
    
    Application.ScreenUpdating = True

но он не подходит, т.к. ищет значение всей ячейки а не только некоторых символов из нее.
Может быть Find использовать, но как реализовать?



0



KoGG

5590 / 1580 / 406

Регистрация: 23.12.2010

Сообщений: 2,366

Записей в блоге: 1

02.02.2017, 15:53

2

Visual Basic
1
X = Replace(X, "11", "22")



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

02.02.2017, 16:22

3

Заменить можно без цикла и поиска

Visual Basic
1
Range("E2:E150").Replace "11", "22", xlPart



1



The_Fog

0 / 0 / 2

Регистрация: 24.02.2016

Сообщений: 75

03.02.2017, 08:54

 [ТС]

4

Заменить можно без цикла и поиска

Visual Basic
1
Range("E2:E150").Replace "11", "22", xlPart

что значит xlPart ?



0



CyberHelp

6 / 6 / 1

Регистрация: 29.01.2017

Сообщений: 29

03.02.2017, 10:26

5

1)

Visual Basic
1
2
3
4
5
6
7
8
Public Sub NaitiNaVsemListe()
 
'proveryaet na liste vse ya4eiki i menyaet 22 na 11
 
    Cells.Replace What:="22", Replacement:="11", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
 
End Sub

2)

Visual Basic
1
2
3
4
5
6
7
8
9
Public Sub NaitiVDiapazone()
 
'nahodit i menyat 22 na 11 v fiksirovannom diapazone "A2:A4"
 
    Range("A2:A4").Select
    Selection.Replace What:="22", Replacement:="11", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

Смотрите вложенный файл.

P.S.
xlPart это атрибут, указывающий искать в ячейке частично, а не всю ячейку целиком обрабатывать, по-английски part = «часть».

Вложения

Тип файла: rar Find.rar (16.1 Кб, 11 просмотров)



1



The_Fog

0 / 0 / 2

Регистрация: 24.02.2016

Сообщений: 75

03.02.2017, 13:19

 [ТС]

6

А если у меня есть столбец 1 А мне нужно получить 2
2 1
1 2
1 2
Я создаю цикл

Visual Basic
1
2
3
4
5
6
7
8
9
Sub Макрос1()
 
 Dim x As Range
    For Each x In Range("E2:E10")
    flag = 0
   x.Replace "1", "2", xlPart
   x.Replace "2", "1", xlPart
Next
End Sub

Получаю весь столбец с 1. Т.е. мне надо чтобы если он заменил в одной ячейке 1 на 2, он переходил к другой и менял там 2 на 1, а не эту же ячейку заменял. Какое условие написать?

Visual Basic
1
if (x.Replace "1", "2", xlPart)=False Then

это неправильно, но нужно что-то типа вот такого как это сделать?

Добавлено через 11 минут
Прошу прощения один столбец нужно заменить другим

1 2
2 1
1 2
1 2



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

03.02.2017, 20:23

7

Лучший ответ Сообщение было отмечено The_Fog как решение

Решение

На небольшом диапазоне можно и так :

Visual Basic
1
2
3
4
5
6
7
8
Dim x As Range
For Each x In Range("E2:E10")
    If x Like "*1*" Then
       x.Replace "1", "2", xlPart
    Else
       x.Replace "2", "1", xlPart
    End If
Next



1



The_Fog

0 / 0 / 2

Регистрация: 24.02.2016

Сообщений: 75

06.02.2017, 11:33

 [ТС]

8

Visual Basic
1
If x Like "*1*" Then

а что значат эти звездочки около 1 =)



0



1024 / 227 / 21

Регистрация: 20.05.2016

Сообщений: 971

Записей в блоге: 19

06.02.2017, 13:19

9



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

06.02.2017, 17:03

10

The_Fog, * это символ подстановки, обозначающий любое количество символов (в т.ч. 0), впрочем, если он Вас «пугает», то замените на If InStr(x, 1) > 0 Then



0



The_Fog

0 / 0 / 2

Регистрация: 24.02.2016

Сообщений: 75

07.02.2017, 15:07

 [ТС]

11

pashulka,

Visual Basic
1
2
3
4
5
6
7
8
Dim x As Range
For Each x In Range("E2:E10")
    If x Like "*1*" Then
       x.Replace "1", "2", xlPart
    Else
       x.Replace "2", "1", xlPart
    End If
Next

Вообще ничего не меняет =(



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

07.02.2017, 18:42

12

The_Fog, А у меня меняет



1



0 / 0 / 2

Регистрация: 24.02.2016

Сообщений: 75

09.02.2017, 17:39

 [ТС]

13

pashulka, Спасибо все работает, просто у меня данные были на 3 листе =) Еще вопрос чтоб темы не плодить, а если ячейки объединенные DE и в символах есть пробелы как делать replace к какой ячейки обращаться?



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

09.02.2017, 19:04

14

The_Fog, Если об’единены ячейки столбцов D и E, то просто перебирайте ячейки столбца D



1



0 / 0 / 2

Регистрация: 24.02.2016

Сообщений: 75

10.02.2017, 12:04

 [ТС]

15

pashulka, Спасибо вам за помощь ! =)



0



Добрый день.
У меня похожая задача, с некоторыми оговорками:

В столбце A — идентификатор документа. Список уникальный и без повторов.
В столбце B — текст документа с идентификаторами номенклатур, где одна и та же номенклатура может повторится больше 1 раза.
В столбце E — список известных идентификаторов номенклатур. Список уникальный и без повторов.

Нужно к списку в столбце E сопоставить документ, в котором есть эта номенклатура.

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

Я пробовал то же самое с формулой, но там есть момент, при котором она работает некорректно, а именно:
При поиске такие номенклатуры как 1id, 11id, 21id,31id и т.д. для формулы одинаковые, если искать просто 1id.
Я также пытался привести столбец B к единому виду, чтобы подготовить список номенклатур в столбик для ВПР. Но тут слишком разнообразен мир написания текстов в ячейках и у номенклатур нет единой маски.
Задача не разовая. Такой список документов надо обрабатывать ежемесячно и в нем в среднем 80тыс строк. В известных номенклатурах количество в среднем 30-40тыс ежемесячно.

Понравилась статья? Поделить с друзьями:
  • Vba переключение листов excel vba
  • Vba пишем макрос для excel
  • Vba передать значение в переменную excel
  • Vba передать диапазон excel в массив
  • Vba параметры страницы excel