Работа с текстом в коде VBA Excel. Функции, оператор &
и другие ключевые слова для работы с текстом. Примеры использования некоторых функций и ключевых слов.
Функции для работы с текстом
Основные функции для работы с текстом в VBA Excel:
Функция | Описание |
---|---|
Asc(строка) | Возвращает числовой код символа, соответствующий первому символу строки. Например: MsgBox Asc(«/Stop»). Ответ: 47, что соответствует символу «/». |
Chr(код символа) | Возвращает строковый символ по указанному коду. Например: MsgBox Chr(47). Ответ: «/». |
Format(Expression, [FormatExpression], [FirstDayOfWeek], [FirstWeekOfYear]) | Преобразует число, дату, время в строку (тип данных Variant (String)), отформатированную в соответствии с инструкциями, включенными в выражение формата. Подробнее… |
InStr([начало], строка1, строка2, [сравнение]) | Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с начала строки. Подробнее… |
InstrRev(строка1, строка2, [начало, [сравнение]]) | Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с конца строки. Подробнее… |
Join(SourceArray,[Delimiter]) | Возвращает строку, созданную путем объединения нескольких подстрок из массива. Подробнее… |
LCase(строка) | Преобразует буквенные символы строки в нижний регистр. |
Left(строка, длина) | Возвращает левую часть строки с заданным количеством символов. Подробнее… |
Len(строка) | Возвращает число символов, содержащихся в строке. |
LTrim(строка) | Возвращает строку без начальных пробелов (слева). Подробнее… |
Mid(строка, начало, [длина]) | Возвращает часть строки с заданным количеством символов, начиная с указанного символа (по номеру). Подробнее… |
Replace(expression, find, replace, [start], [count], [compare]) | Возвращает строку, полученную в результате замены одной подстроки в исходном строковом выражении другой подстрокой указанное количество раз. Подробнее… |
Right(строка, длина) | Возвращает правую часть строки с заданным количеством символов. Подробнее… |
RTrim(строка) | Возвращает строку без конечных пробелов (справа). Подробнее… |
Space(число) | Возвращает строку, состоящую из указанного числа пробелов. Подробнее… |
Split(Expression,[Delimiter],[Limit],[Compare]) | Возвращает одномерный массив подстрок, извлеченных из указанной строки с разделителями. Подробнее… |
StrComp(строка1, строка2, [сравнение]) | Возвращает числовое значение Variant (Integer), показывающее результат сравнения двух строк. Подробнее… |
StrConv(string, conversion) | Изменяет регистр символов исходной строки в соответствии с заданным параметром «conversion». Подробнее… |
String(число, символ) | Возвращает строку, состоящую из указанного числа символов. В выражении «символ» может быть указан кодом символа или строкой, первый символ которой будет использован в качестве параметра «символ». Подробнее… |
StrReverse(строка) | Возвращает строку с обратным порядком следования знаков по сравнению с исходной строкой. Подробнее… |
Trim(строка) | Возвращает строку без начальных (слева) и конечных (справа) пробелов. Подробнее… |
UCase(строка) | Преобразует буквенные символы строки в верхний регистр. |
Val(строка) | Возвращает символы, распознанные как цифры с начала строки и до первого нецифрового символа, в виде числового значения соответствующего типа. Подробнее… |
WorksheetFunction.Trim(строка) | Функция рабочего листа, которая удаляет все лишние пробелы (начальные, конечные и внутренние), оставляя внутри строки одиночные пробелы. |
В таблице перечислены основные функции VBA Excel для работы с текстом. С полным списком всевозможных функций вы можете ознакомиться на сайте разработчика.
Ключевые слова для работы с текстом
Ключевое слово | Описание |
---|---|
& | Оператор & объединяет два выражения (результат = выражение1 & выражение2). Если выражение не является строкой, оно преобразуется в Variant (String), и результат возвращает значение Variant (String). Если оба выражения возвращают строку, результат возвращает значение String. |
vbCrLf | Константа vbCrLf сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит последующий текст на новую строку (результат = строка1 & vbCrLf & строка2). |
vbNewLine | Константа vbNewLine в VBA Excel аналогична константе vbCrLf, также сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит текст на новую строку (результат = строка1 & vbNewLine & строка2). |
Примеры
Вывод прямых парных кавычек
Прямые парные кавычки в VBA Excel являются спецсимволами и вывести их, заключив в самих себя или в одинарные кавычки (апострофы), невозможно. Для этого подойдет функция Chr:
Sub Primer1() ‘Вывод одной прямой парной кавычки MsgBox Chr(34) ‘Отображение текста в прямых кавычках MsgBox Chr(34) & «Волга» & Chr(34) ‘Вывод 10 прямых парных кавычек подряд MsgBox String(10, Chr(34)) End Sub |
Смотрите интересное решение по выводу прямых кавычек с помощью прямых кавычек в первом комментарии.
Отображение слов наоборот
Преобразование слова «налим» в «Милан»:
Sub Primer2() Dim stroka stroka = «налим» stroka = StrReverse(stroka) ‘милан stroka = StrConv(stroka, 3) ‘Милан MsgBox stroka End Sub |
или одной строкой:
Sub Primer3() MsgBox StrConv(StrReverse(«налим»), 3) End Sub |
Преобразование слова «лето» в «отель»:
Sub Primer4() Dim stroka stroka = «лето» stroka = StrReverse(stroka) ‘отел stroka = stroka & «ь» ‘отель MsgBox stroka End Sub |
или одной строкой:
Sub Primer5() MsgBox StrReverse(«лето») & «ь» End Sub |
Печатная машинка
Следующий код VBA Excel в замедленном режиме посимвольно печатает указанную строку на пользовательской форме, имитируя печатную машинку.
Для реализации этого примера понадобится пользовательская форма (UserForm1) с надписью (Label1) и кнопкой (CommandButton1):
Код имитации печатной машинки состоит из двух процедур, первая из которых замедляет выполнение второй, создавая паузу перед отображением очередного символа, что и создает эффект печатающей машинки:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Sub StopSub(Pause As Single) Dim Start As Single Start = Timer Do While Timer < Start + Pause DoEvents Loop End Sub Private Sub CommandButton1_Click() Dim stroka As String, i As Byte stroka = «Печатная машинка!» Label1.Caption = «» For i = 1 To Len(stroka) Call StopSub(0.25) ‘пауза в секундах ‘следующая строка кода добавляет очередную букву Label1.Caption = Label1.Caption & Mid(stroka, i, 1) Next End Sub |
Обе процедуры размещаются в модуле формы. Нажатие кнопки CommandButton1 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.
String manipulation is a crucial skill in VBA programming. The skill level of a VBA developer is often determined by how well he/she can manipulate string data. Excel is very strong in mathematics operations and comes with loads of built-in calculation functions. But text manipulation is less straightforward and always requires some creativity and experience.
In this article, I am going to show you how to remove characters from strings. We’ll go through a series of common scenarios, and you’ll learn about how to tackle them with the Replace, Left, Right, Trim, and Instr VBA functions.
Remove All Occurrences of Specific Characters from Strings
The basic VBA skill to remove characters from a string is with the Replace method.
The basic syntax of VBA Replace method you need to remember is:
Replace (inputString, findwhat, replace)
Example 1 is the most typical approach where the Replace method is used to remove all occurrences of specific character(s) from the input string.
Example 1 – The Most Common Approach, Case Sensitive
Here we want to remove all occurrence of “b” from variable input1,”aabbccAABBCC”, with the expected output of “aaccAABBCC”. In line 6 of the macro, the Replace method looks for “b” and replaces it with an empty string “”.
Sub removechar() Dim input1 As String Dim result As String input1 = "aabbccAABBCC" 'to remove all occurrences of b from input string result = Replace(input1, "b", "") MsgBox result End Sub
After running the macro, the answer is displayed in the message box:
However, this approach with the Replace method is case sensitive. Only the lower case “b” characters were removed but not the “B”. We can modify our macro to automatically handle both lower and upper cases.
Example 2 – Simple Non-Case Sensitive Approach
We can enhance the macro to remove both the lower case “b” and upper case “B” from the input string. In macro removechar2
below, the character to be remove is defined in line 6. Then, in line 7, we first remove the lower case, and then in line 8 the upper case is also removed.
Sub removechar2() Dim input1 As String Dim remove1 As String Dim result As String input1 = "aabbccaabbcc" remove1 = "b" 'this is the char to be removed result = Replace(input1, LCase(remove1), "") result = Replace(result, UCase(remove1), "") MsgBox result End Sub
Remove the First n Occurrences of Specific Characters from Strings
Sometimes we want to remove only the first n occurrences of specific characters. This is easy to do by using the optional argument “count” of the VBA Replace method:
Syntax:
Replace (inputString, findwhat, replace, start_position, count)
The following macro “removechar3” removes the first 3 occurrences of “b” from input1 “aabbccaabbcc”. The expected result is “aaccaabcc”.
Sub removechar3() Dim input1 As String Dim remove1 As String Dim result As String input1 = "aabbccaabbcc" remove1 = "b" 'remove the first 3 occurrences of "b" from input string result = Replace(input1, remove1, "", , 3) MsgBox result End Sub
After running the macro, the answer is displayed in the message box:
Remove Characters from Left of Strings
Here we have a list of staff IDs in the format “X12345678” with 9 characters each. We want to remove the leading letter from every ID in the list.
We can use the Right function for this purpose. While each staff ID is 9 characters long, removing 1 character from the left is equivalent to outputting 8 (9 minus 1) characters from the right.
Sub removeLeft() Dim cell As Range Dim MyRange As Range Dim tmp As String Set MyRange = Selection 'this is your range of data 'loop through every cell in range and remove 1 char from left For Each cell In MyRange.Cells tmp = cell.Value 'output n - 1 characters from the right cell.Value = Right(tmp, Len(tmp) - 1) Next End Sub
However, after running the above macro, we realize that it did not fully meet our expectations (see the picture below). Because some of the original IDs have numeric parts with leading zeros. (Lines 1, 5 and 7), Excel is too clever and automatically trims those zeros. (e.g. 021 is treated by Excel as 21.) We want to make sure the zeros remain after the leading letters were removed.
We can achieve this by forcing Excel to treat numeric data as strings by adding a leading apostrophe to the result. For example, ‘021 will be treated by Excel as string. To achieve this, we can modify line 9 of the macro as shown below:
Sub removeLeft() Dim cell As Range Dim MyRange As Range Dim tmp As String Set MyRange = Selection 'this is your range of data 'loop through every cell in range and remove 1 char from left For Each cell In MyRange.Cells tmp = cell.Value 'output n-1 char from the right, and add apostrophe cell.Value = "'" &amp; Right(tmp, Len(tmp) - 1) Next End Sub
Remove Characters from Right of Strings
Example 1 – Remove a Fixed Number of Characters from the Right
To remove a fixed number of characters x from the right of strings, you can use the LEFT function. The macro is almost the same as the macro above for removing characters from the left.
Sub removeRight() Dim cell As Range Dim MyRange As Range Dim tmp As String Set MyRange = Selection 'this is your range of data 'loop through every cell in range and remove 1 char from right For Each cell In MyRange.Cells tmp = cell.Value 'output n - 1 characters from the left cell.Value = Left(tmp, Len(tmp)-3) Next End Sub
Example 2 – Remove a Variable Number of Characters from the Right
If we want to remove characters from the right based on the variable position of a certain character(s), we can use the INSTR function in conjunction with the LEFT function.
Here we have a list of email addresses. We want to remove the domain names on the right of each address.
We can find out the position of “@” with the following VBA statement, which in the case returns 9. Therefore, to remove the domain name, we have to extract the first 8 characters.
x = Instr("[email protected]","@")
The following macro loops through every cell in a selected range and removes the domain names.
Sub removeDomain() Dim cell As Range Dim MyRange As Range Dim tmp As String Set MyRange = Selection 'this is your range of data 'loop through every cell in range and remove characters after @ For Each cell In MyRange.Cells tmp = cell.Value ' cell.Value = Left(tmp, InStr(tmp, "@") - 1) Next End Sub
Here’s a couple key takeaways to remember about removing characters from one side or the other of strings:
Scenario | Function to be used |
Remove characters from the Left | RIGHT |
Remove characters from the Right | LEFT |
Position specific remove | INSTR (+ LEFT/RIGHT) |
Removing Unwanted Spaces from Strings
There are two common scenarios where we want to remove unwanted spaces from strings:
- Strings with leading and trailing spaces
- Unwanted extra spaces within string (e.g. double spaces)
Remove Leading and Trailing Spaces from Strings
We can use the Trim function to remove leading and trailing spaces. In the example below we have an input string of " This is my data "
(line 5). The Trim function is used in line 6. The macro produces a message box to show a comparison of the input and output.
Sub removespace1() Dim MyInput As String Dim result As String 'here is the input string with leading and trailing spaces MyInput = " This is my data " result = Trim(MyInput) 'remove leading and trailing spaces 'display result in msgbox MsgBox "Original text: &gt;" &amp; MyInput &amp; "&lt;" &amp; Chr(10) &amp; _ "Original length: " &amp; Len(MyInput) &amp; Chr(10) &amp; _ "Final text: &gt;" &amp; result &amp; "&lt;" &amp; Chr(10) &amp; _ "Final length: " &amp; Len(result) End Sub
Removing “extra spaces” is different from removing “all spaces.” You can visualize the difference here:
The macro removeAllUnwantedSpace
below removes leading and trailing spaces as well as all unwanted repeated spaces. Pay special attention to line 10 to 12. The same statement must be run 3 times to ensure all repeated spaces are replaced with single spaces.
Sub removeAllUnwantedSpace() Dim MyInput As String Dim result As String 'here is the input string with unwanted spaces MyInput = " This is my data " 'first remove leading and trailing spaces result = Trim(MyInput) 'then replace double spaces with single space 'this step has to be repeated 3 times result = Replace(result, " ", " ") result = Replace(result, " ", " ") result = Replace(result, " ", " ") 'display result in msgbox MsgBox "Original text: &gt;" &amp; MyInput &amp; "&lt;" &amp; Chr(10) &amp; _ "Original length: " &amp; Len(MyInput) &amp; Chr(10) &amp; _ "Final text: &gt;" &amp; result &amp; "&lt;" &amp; Chr(10) &amp; _ "Final length: " &amp; Len(result) End Sub
Remove Numbers from String
Sometimes we want to remove all numeric characters from strings. We can achieve this with a For-Next loop to remove each of the digits from 0 to 9.
The custom VBA function below shows how to remove all numeric characters from an input string.
Function removenumbers(ByVal input1 As String) As String Dim x Dim tmp As String tmp = input1 'remove numbers from 0 to 9 from input string For x = 0 To 9 tmp = Replace(tmp, x, "") Next 'return the result string removenumbers = tmp End Function
You could also consider using a regular expression for a task like this.
Remove line breaks from string
Sometimes our data may contain line breaks with the strings and we want to remove them. A line break is actually an invisible character. We can simply use the VBA Replace function to remove them.
There are 2 types of line break characters. The most common one is Chr(10). But a less common one is Chr(13). Chr(13) is more common on the Mac. We can use a statement like this to remove such line break characters:
result = Replace(myString, Chr(10)) 'or result = Replace(Replace(myString, Chr(10)), Chr(13))
Remove Accented Characters from Names
There is a special situation that we want to remove the “accent” from accented characters in names. As an example, we have a list of French names below. In this case, we want to stick to “regular” English letters. Our expected result is shown on the right.
The macro “removeAccented
” below loops through every cell in a selected range and replaces all accented characters with the corresponding regular English letters.
At the beginning of the macro, two constant strings were defined: “Accent” holds all accented characters; and “Normal” holds the corresponding regular English letters.
The For-Next loop (which begins in line 13 of code) loops through every accented character in the constant “Accent” and replaces with the alphabet in the same position in the constant “Normal”, e.g. “à” which is in position 1 of “Accent” will be replaced with “a” in position 1 of “Normal”.
Sub removeAccented() Const Accent = _ "àáâãäåçèéêëìíîïðñòóôõöùúûüýÿŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝ" Const Normal = _ "aaaaaaceeeeiiiidnooooouuuuyySZszYAAAAAACEEEEIIIIDNOOOOOUUUUY" Dim cell As Range Dim x As Integer Dim tmp As String 'loop through each cell in selection For Each cell In Selection.Cells tmp = cell.Value 'loop through the constants, and replace For x = 1 To Len(Accent) tmp = Replace(tmp, Mid(Accent, x, 1), Mid(Normal, x, 1)) Next cell.Value = tmp Next End Sub
Conclusion
You can see in the above examples that text manipulation in Excel VBA indeed requires some creativity. There is no single universal approach to remove characters from strings which can serve all scenarios. The Replace function is the most important function to use. In some cases, you also have to apply the Left, Right, Trim, Instr functions.
The technique to loop through cells in a range has also been used in most of the examples above. You may refer to my article on this topic for more examples on the topic.
Tagged with: Characters, InStr, LEFT, Line Breaks, Replace, RIGHT, Spaces, String Processing, Strings, Substring, Trimming, VBA
Евгений Пользователь Сообщений: 11 |
Добрый день. Нужно написать макрос, который удаляет определенные символы (напримео XX) в начале каждой ячейки диапазона. Например: В какую сторону можно копать? |
Ham13 Пользователь Сообщений: 88 |
Выносишь в доп столбец (или в массив если макрос) первые два символа, там где в доп столбце символы равны ХХ, меняешь значение в основном столбце |
artemkau88 Пользователь Сообщений: 552 |
#3 05.11.2022 20:30:49 Евгений
, добрый вечер!
Прикрепленные файлы
|
||
Евгений Пользователь Сообщений: 11 |
Всем спасибо! Ham13 подсказал нужное направление, я сделал так: If rangeItem.Value Like (stringToDel & «*») Then |
Евгений Пользователь Сообщений: 11 |
#5 05.11.2022 20:46:26 Вот функция полностью:
Изменено: Евгений — 05.11.2022 20:47:45 |
||
New Пользователь Сообщений: 4581 |
#6 06.11.2022 01:32:34 допустим в ячейке А2 находится текст «XX123», тогда в ячейку В2 вводим =DeleteFirstSymbols(A2;»XX»)
|
||
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#7 07.11.2022 10:00:37 artemkau88, очень странно использовать для этого RegExp…
Изменено: Jack Famous — 07.11.2022 10:02:14 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
|
Jack Famous
, почему? Думаю регулярками в разы проще задачи со строками решать, или я ошибаюсь. Изменено: artemkau88 — 07.11.2022 10:05:56 |
|
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
artemkau88, для использования регулярок, нужно, как минимум, знать правило создания шаблона для работы вашей «готовой» функцией. Для подобной задачи, это вообще не нужно, т.к. строковыми и понятнее и быстрее. Изменено: Jack Famous — 07.11.2022 10:11:04 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
Jack Famous
, согласен, не все знают регулярки, и я тоже в их числе (глубоко не заглублялся пока) Функцию написал,
обновил еще раз(см. вложение) Изменено: artemkau88 — 07.11.2022 10:31:35 |
|
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#11 07.11.2022 10:26:00
Вариант, конечно, рабочий, но, как я уже ранее сказал, не вижу смысла усложнять на ровном месте… А также: 1. если .Global = False, то зачем .MultiLine = True Изменено: Jack Famous — 07.11.2022 10:29:09 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
|
Jack Famous
, абсолютно согласен, обновил сообщение выше. |
|
Ігор Гончаренко Пользователь Сообщений: 13746 |
#13 07.11.2022 10:32:48
Изменено: Ігор Гончаренко — 07.11.2022 10:39:23 Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
Ігор Гончаренко, то же, что и в #6 , но дольше работать будет Изменено: Jack Famous — 07.11.2022 10:35:19 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
)) Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
|
ocet p Пользователь Сообщений: 438 |
#16 08.11.2022 00:46:27 такой вариант:
время перехода при обработке данных (1 миллион строк) в переменной массива: запуск/вызов (?) функции (на основе одного символа — не подходит для «смешанных символов», таких как: Xa, Xx, и т. д.):
|
||||
New Пользователь Сообщений: 4581 |
ocet p, у меня на 1млн строк («X123») вот так Изменено: New — 08.11.2022 01:39:35 |
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
New, там вообще всё очень неоптимально… ocet p, прошу прощения — тесты показывают преимущество вашего подхода для удаления повторяющихся символов. Изменено: Jack Famous — 08.11.2022 09:51:06 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#19 08.11.2022 09:56:15
ocet p, спасибо за науку! Изменено: Jack Famous — 08.11.2022 11:38:01 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
||||
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
RAN, спасибо — очень интересно, но надо проверять самому. В любом случае, изучу Изменено: Jack Famous — 08.11.2022 11:38:47 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
ocet p Пользователь Сообщений: 438 |
#22 08.11.2022 15:08:08
на моей «машиночке» всё в три-четыре раза длиннее работает, она уже старинная — ваша это «быстрая машина»
рад, что привнес что-то в тему |
||||
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#23 09.11.2022 13:08:39
не со всем согласен: в основном, кажется, что выигрыш сильно завышен. Может, это было актуально когда-то давно, но не сейчас. Каждое утверждение должно сопровождаться кодом — чтобы можно было сразу проверить обоснованность вывода. Часто, только по тексту теста (без исполнения) можно понять, что он некорректный/неполный.
Я вообще стараюсь использовать For Each только для перебора ключей словаря. Например For Each по большому количеству областей может вызвать ошибку, а счётчик такого никогда не допустит. Думаю, разница в том, что для For Each нужно сначала определить коллекцию, которую он будет перебирать и это не всегда получается…
В общем, доверяй, но проверяй (и подтверждай) Изменено: Jack Famous — 09.11.2022 13:21:24 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
||||||||||
Jack Famous
, позвольте вопрос: а как же сложность алгоритма по которому выполняется код? Или им можно пренебречь, если знать все эти тонкости (из Вашего сообщения выше) и сверх этого? |
|
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#25 09.11.2022 13:53:24
не понял вопроса… Изменено: Jack Famous — 09.11.2022 13:53:49 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
||
artemkau88 Пользователь Сообщений: 552 |
#26 09.11.2022 14:06:10 Я имею в виду худшее время выполнения кода в нотации О большое, например: P.S:
один цикл не всегда лучше, чем 2, смотря что использовать внутри цикла Прикрепленные файлы
Изменено: artemkau88 — 09.11.2022 14:59:48 |
||
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#27 09.11.2022 15:01:31 artemkau88, какого кода, какая нотация — вы о чём??? Темой не ошиблись?
откуда мне знать, как использование других приёмов повлияет на вашу сортировку? Пробуйте… При тестировании различных методик, всё остальное отметается для чистоты замера. Вы проезжаете 100 км за 2 часа. Средняя скорость 50 км/ч. Но вы едете и 150 и 20 км/ч — на разных участках. Изменено: Jack Famous — 09.11.2022 15:06:36 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
||
artemkau88 Пользователь Сообщений: 552 |
#28 09.11.2022 15:05:43 Да, прошу прощения, перетрудился я чего-то наверное.
понял, спасибо! Изменено: artemkau88 — 09.11.2022 15:06:21 |
||
Jack Famous Пользователь Сообщений: 10846 OS: Win 8.1 Корп. x64 | Excel 2016 x64: | Browser: Chrome |
#29 09.11.2022 15:07:59
artemkau88, пользуйтесь на здоровье Изменено: Jack Famous — 09.11.2022 15:30:22 Во всех делах очень полезно периодически ставить знак вопроса к тому, что вы с давних пор считали не требующим доказательств (Бертран Рассел) ►Благодарности сюда◄ |
|
artemkau88 Пользователь Сообщений: 552 |
#30 09.11.2022 15:09:21
да, спасибо!
Большое спасибо! |
||||
You can remove characters by replacing a character with an empty string («»). Although you can do this by going through all such cells in a selection or specified range using Find & Replace, in this article we’re going to show you how to remove characters in Excel using VBA. This method can help you integrate this with other calculations and automate the process.
How to remove characters in Excel using VBA
There are 2 separate functions that we need to look at here:
- Find
- Replace
We need to use the Replace method to perform a removing action. For this, there are two parameters we should focus:
- What: String that we want to remove
- Replacement: Replacement value, which should be an empty string («») for removing the characters
You can assign these values into variables, or directly use them as an argument which is the case in the sample code we’re going to be using.
Alternatively, you can replace within a predetermined range, instead of a selected range. To do this, replace the Selection object with a Range object. You can find both examples at below.
You can use the code in two ways:
- Module
- Immediate Window
In the Module method, you need to add the module into the workbook or the add-in file. Copy and paste the code into the module to run it. The main advantage of the module method is that it allows saving the code in the file, so that it can be used again later. Furthermore, the subroutines in modules can be used by icons in the menu ribbons or keyboard shortcuts. Remember to save your file in either XLSM or XLAM format to save your VBA code.
The Immediate Window method, on the other hand, is essentially a quick and dirty method where you can simply copy and paste the code into the Immediate Window and press the Enter key to run it. Unfortunately, any code you use in the Immediate Window will not be saved. Also note that icons and keyboard shortcuts will not be available.
Remove a character in a selection
Module Version:
Sub RemoveCharacterInSelection Dim oldValue As String, newValue As String oldValue = "e" newValue = "" 'Because we want to remove 'oldValue and newValue variables are used as arguments Selection.Cells.Replace What:= oldValue, Replacement:= newValue, _ LookAt:=xlPart, SearchOrder:=xlByRows, _ MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False End Sub
Immediate Window version (no variables):
Selection.Cells.Replace What:="e", Replacement:="", _ LookAt:=xlPart, SearchOrder:=xlByRows, _ MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Remove a character in a specified range
Module Version:
Sub RemoveCharacterInRange Dim oldValue As String, newValue As String, rng as Range oldValue = "e" newValue = "" 'Because we want to remove Set rng = Range("B2:E11") 'Replace action takes in rng range rng.Cells.Replace What:= oldValue, Replacement:= newValue, _ LookAt:=xlPart, SearchOrder:=xlByRows, _ MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False End Sub
Immediate Window version (no variables):
Range("B2:E11").Cells.Replace What:="e", Replacement:="", _ LookAt:=xlPart, SearchOrder:=xlByRows, _ MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False