Перейти до основного матеріалу

Знайдіть n-те входження символу в Excel – 3 швидких способи

Автор: Сяоян Остання зміна: 2024-04-24

Пошук n-го входження певного символу в текстовому рядку в Excel може бути особливо корисним під час аналізу даних, де вам може знадобитися проаналізувати рядки або витягти інформацію на основі певних роздільників або шаблонів. Наприклад, давайте знайдемо 2-е або 3-є входження символу "-" в текстовому рядку. Я продемонструю прості методи ефективного виконання цього завдання.


Знайдіть n-е входження символу в текстовому рядку за допомогою формули

Ви можете створити формулу для знаходження n-го повторення символу. Будь ласка, зробіть так:

1. Введіть або скопіюйте наступну формулу в клітинку, де ви хочете отримати результат:

=FIND(CHAR(1),SUBSTITUTE(A2,"-",CHAR(1),2))
примітки: У наведеній вище формулі:
  • A2: клітинка, яка містить рядок.
  • -: персонаж, якого ви шукаєте.
  • 2: 2-й випадок, який ви хочете знайти, ви можете змінити його на 3,4…як вам потрібно.

2. Потім перетягніть заливку формули вниз, щоб заповнити формулу іншими комірками, і 2-а позиція символу – відображаються відразу, дивіться знімок екрана:

Пояснення формули:
  • ЗАМІННИК замінює n-е входження символу на недрукований символ (CHAR(1)).
  • ЗНАЙТИ шукає цей недрукований символ, надаючи позицію n-го входження.

Знайдіть n-те входження символу в текстовий рядок за допомогою Kutools для Excel

Якщо ви не любитель використовувати формулу або VBA, ви можете розглянути зручну альтернативу – Kutools для Excel. У групах формул ви знайдете корисну утиліту – Знайдіть, де символ відображається N-й у рядку який швидко визначає та повертає n-ту позицію будь-якого символу в клітинці.

Після встановлення Kutools для Excel, Натисніть Кутулс > Помічник формули > Помічник формули відкрити Помічник формули діалогове вікно. Клацніть клітинку, куди потрібно помістити результат. Потім виконайте наступне:

  1. Select Пошук з розкривного списку Тип формули розділ;
  2. Вибирати Знайдіть, де символ відображається N-й у рядку in Виберіть формулу розділ;
  3. Виберіть комірку, яка містить рядок, який ви використовуєте, а потім введіть вказаний символ і n-е входження в текстові поля в Введення аргументів розділ;
  4. Нарешті клацніть OK кнопку, щоб отримати результат.

Знайдіть n-те входження символу в текстовий рядок за допомогою функції, визначеної користувачем

У цьому розділі ми розглянемо, як створити та використати UDF для пошуку n-го повторення символу в Excel, надавши покроковий посібник, який допоможе вам оптимізувати обробку даних.

  1. Утримуйте клавішу ALT + F11 і відкриває Microsoft Visual Basic для додатків вікна.
  2. Натисніть Insert > Модуліта вставте наступний макрос у вікно модуля.
     Function FindN(sFindWhat As String, _
    sInputString As String, N As Integer) As Integer
    'Updateby Extendoffice
    Dim J As Integer
    Application.Volatile
    FindN = 0
    For J = 1 To N
    FindN = InStr(FindN + 1, sInputString, sFindWhat)
    If FindN = 0 Then Exit For
    Next
    End Function
  3. Потім закрийте вікно vba. Поверніться до робочого аркуша, введіть наведену нижче формулу в клітинку, а потім перетягніть маркер заповнення вниз, щоб заповнити формулою інші клітинки, див. знімок екрана:
    =FindN("-",A2,3)

  4. Статті по темі:

    • Підрахуйте кількість входжень слова в стовпчик
    • Якщо у вас є дані стовпця, які містять кілька повторюваних значень, як показано на знімку екрана, а тепер ви хочете підрахувати кількість повторень конкретного слова в цьому стовпці. Тепер у цьому підручнику я представляю деякі трюки, щоб швидко вирішити це питання в Excel.
    • Витягти n-й символ із рядка
    • Загалом, ви можете витягнути рядок після певного символу, але в цьому випадку я хочу витягти n-й символ із рядка, як показано на знімку екрана нижче.
    • Витягти перші/останні n символів із рядка
    • Наприклад, у кожній комірці є список з довгими рядками, і ви хочете витягти перші n символів лише з кожного рядка, як перші 3 символи кожного рядка, і тепер ви можете використовувати наступні методи для його вирішення в Excel .

Найкращі інструменти продуктивності офісу

🤖 Kutools AI Aide: Революціонізуйте аналіз даних на основі: Інтелектуальне виконання   |  Згенерувати код  |  Створення спеціальних формул  |  Аналізуйте дані та створюйте діаграми  |  Викликати функції Kutools...
Популярні функції: Знайдіть, виділіть або визначте дублікати   |  Видалити порожні рядки   |  Об’єднайте стовпці або клітинки без втрати даних   |   Раунд без Формули ...
Супер пошук: VLookup за кількома критеріями    Багатозначний VLookup  |   VLookup на кількох аркушах   |   Нечіткий пошук ....
Розширений розкривний список: Швидке створення випадаючого списку   |  Залежний спадний список   |  Виберіть розкривний список, що вибирається ....
Менеджер колонок: Додайте конкретну кількість стовпців  |  Перемістити стовпці  |  Перемкнути статус видимості прихованих стовпців  |  Порівняйте діапазони та стовпці ...
Особливості: Фокус сітки   |  Перегляд дизайну   |   Велика панель формул    Диспетчер робочих книг і аркушів   |  Бібліотека ресурсів (автотекст)   |  Вибір дати   |  Об’єднайте робочі аркуші   |  Шифрування/розшифрування клітинок    Надсилайте листи за списком   |  Супер фільтр   |   Спеціальний фільтр (фільтр жирний/курсив/закреслений...) ...
Топ-15 наборів інструментів12 текст Tools (додати текст, Видалити символи, ...)   |   50 + Графік типи (діаграма Ганта, ...)   |   40+ Практичний Формули (Розрахуйте вік на основі дня народження, ...)   |   19 вставка Tools (Вставте QR-код, Вставити зображення зі шляху, ...)   |   12 Перетворення Tools (Числа до слів, Валютна конверсія, ...)   |   7 Злиття та розділення Tools (Розширені комбіновані ряди, Розділені клітини, ...)   |   ... і більше

Покращуйте свої навички Excel за допомогою Kutools для Excel і відчуйте ефективність, як ніколи раніше. Kutools для Excel пропонує понад 300 додаткових функцій для підвищення продуктивності та економії часу.  Натисніть тут, щоб отримати функцію, яка вам найбільше потрібна...

Опис


Вкладка Office Передає інтерфейс із вкладками в Office і значно полегшує вашу роботу

  • Увімкніть редагування та читання на вкладках у Word, Excel, PowerPoint, Publisher, Access, Visio та Project.
  • Відкривайте та створюйте кілька документів на нових вкладках того самого вікна, а не в нових вікнах.
  • Збільшує вашу продуктивність на 50% та зменшує сотні клацань миші для вас щодня!
Comments (28)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Your formula to find the Nth occurrence of a character in a string does not work. Using your example, adding 2 to the results of the imbedded find ensures a starting position for the initial find of a position beyond the 1st two c's but changing the +2 to +3 does not yield the position of the 4th "c", it simply starts the search one character deeper into the string and the result is still the 3rd "c". To find the 4th "c" the search must begin beyond the position of the 3rd "c". I look forward to your new solution.
This comment was minimized by the moderator on the site
Hello, David

Yes, as you said, the first formula does not work correctly, you can apply the second formula:
=FIND(CHAR(1),SUBSTITUTE(A2,"c",CHAR(1),2))

Note: The number "2" in the formula means the second "c", if you want to get the third, fourth "c", just change the number 2 to 3,4 as you need.
Please try, hope it can help you!
This comment was minimized by the moderator on the site
Find formula1 is imperfect. It will be a great help if it is removed. I have lost lot of time trying for 4th occurance of "a" in "vedanarayanan" Thanks.
This comment was minimized by the moderator on the site
To handle the exception of the formula, you can use same with if and iserro
=IF(ISERR(FIND("c",A1,FIND("c",A1)+2)),FIND("c",A1,FIND("c",A1)+0),FIND("c",A1,FIND("c",A1)+2))
This comment was minimized by the moderator on the site
"Substitute" lets you find the Nth occurrence of a term, so combine it with "find" as follows (where 5=5th occurrence):

=FIND(CHAR(1),SUBSTITUTE(A1,"c",CHAR(1),5))
This comment was minimized by the moderator on the site
Excellent! I am glad I scrolled up to review other comments after posting my own.
This comment was minimized by the moderator on the site
This is the correct answer! please replace this whole article with this one line of code.....
This comment was minimized by the moderator on the site
The first formula is completely useless and wrong but it works just correct for this example as the first and second "c"s are adjacent. The correct formula is:


For 2nd occurence -
=FIND("c",A1,FIND("c",A1)+1)

For 3rd occurence -
=FIND("c",A1,FIND("c",A1,FIND("c",A1)+1)+1) and so on...
This comment was minimized by the moderator on the site
Absolutely agree. The +2, or +3 etc.....entirely depends on the spacing between the n and (n+1) occurences of "c". Thus you would have to manually adjust for every cell if you were trying to copy this formula down a column for instance. Essentially the same as manually counting.


Ex. Let's try to find the 4th occurrence of "c" in cell A1 using the provided formula. Per the article we should use +3 in our nested FIND function to find the 4th occurrence.


Text in Cell A1:

"cab car abc cole cube"

Manually counting, the 4th occurrence is the "c" in cole in the character position of 13.


=FIND("c",A1,FIND("c",A1)+3)

The nested function, FIND("c",A1) will find the first occurrence of "c" in position 1.

Therefore,

FIND("c",A1)+3 = 1+3 = 4

Plugging that back into our formula,

=FIND("c",A1,FIND("c",A1)+3) = FIND("c",A1,1+3) = FIND("c",A1,4)

This new formula will look for the first occurrence of "c" beginning from character position 4. The 4th character in the string is the space just after cab.

Therefore, the formula will find the "c" in car and return the value of 5 for our formula. As we know from manually counting we are looking for 13 as the output.
This comment was minimized by the moderator on the site
The firs formula works correct in my version, in the note, it has explained how to find the third or forth or nth "c".

Note: You can change the 2 in the formula based on your needs. For example, if you want to find the fourth position of "c", you can change the 2 to 3. And if you want to find the first position of "c", you shuold change 2 to 0.
This comment was minimized by the moderator on the site
Try to find out the position of the second c with the first sentence of my above comment as the string using the first formula. You'll get to know how correct it is!
This comment was minimized by the moderator on the site
Hello all,

I have a text in an Excel cell " BY TRANSFER-NEFT*HDFC0000001*N08745987123546*J0032331*KUMAR--"

I need a function to extract just "N08745987123546"

Thanks
This comment was minimized by the moderator on the site
Hello, do you want to extract the numbers after No and the number of numbers are fixed? If so, you can use Kutools for Exccel's Extract text function, type No????to extract.
This comment was minimized by the moderator on the site
HI ALL,
I have a text in an Excel cell " BY TRANSFER-NEFT*HDHC0065431*N053112345624801*K0038331*krishna--"
I need a function to extract just "N053112345624801"
This comment was minimized by the moderator on the site
Formula 1 doesn't work on fourth, fifth, sixth etc. so (+3,4,5) will always show third position of letter "c" which is 19 second formula is working though.
This comment was minimized by the moderator on the site
Hello all, I have a text in an Excel cell "23 floyd lane, longville,KN 14564" I need a function to extract just "longville" Thanks
This comment was minimized by the moderator on the site
If you must use a function, try: =TRIM(MID(A1,SEARCH(",",A1)+1,SEARCH("!@#",SUBSTITUTE(A1,",","!@#",2))-SEARCH(",",A1)-1)) Otherwise, you might consider Data > Text to Columns > Delimited (using a comma as the separator).
This comment was minimized by the moderator on the site
Try this: =INDEX(SMALL(IF(MID(A1,MATCH(ROW(INDIRECT(1&":"&LEN(A1))),ROW(INDIRECT(1&":"&LEN(A1))),0),1)="c",MATCH(ROW(INDIRECT(1&":"&LEN(A1))),ROW(INDIRECT(1&":"&LEN(A1))),0),""),MATCH(ROW(INDIRECT(1&":"&LEN(A1)-LEN(SUBSTITUTE(A1,"c","")))),ROW(INDIRECT(1&":"&LEN(A1)-LEN(SUBSTITUTE(A1,"c","")))),0)),2) where "c" is the character required and 2 is the position. Note this is an array formula.
This comment was minimized by the moderator on the site
this is simpler: =INDEX(SMALL(IF(MID(A1,ROW(INDIRECT(1&":"&LEN(A1))),1)="c",ROW(INDIRECT(1&":"&LEN(A1))),""),ROW(INDIRECT(1&":"&LEN(A1)-LEN(SUBSTITUTE(A1,"c",""))))),2)
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations