Как удалить символ в строке vba excel

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:

aaccAABBCC

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

aaccAACC

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:

aaccaabcc

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.

List of staff IDs in Excel

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.

Example with highlighted rows

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 = "'" & Right(tmp, Len(tmp) - 1)
Next
End Sub

IDs after processing in a list

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.

List of emails to process

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: >" & MyInput & "<" & Chr(10) & _
    "Original length: " & Len(MyInput) & Chr(10) & _
    "Final text: >" & result & "<" & Chr(10) & _
    "Final length: " & Len(result)
End Sub

Messagebox showing before and after with spaces trimmed

Removing “extra spaces” is different from removing “all spaces.” You can visualize the difference here:

Example string with every single space removed

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: >" & MyInput & "<" & Chr(10) & _
    "Original length: " & Len(MyInput) & Chr(10) & _
    "Final text: >" & result & "<" & Chr(10) & _
    "Final length: " & Len(result)
End Sub

Messagebox showing spaces removed

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


You can use the Replace() method in VBA to remove characters from a string.

The following examples show how to use this method in practice with the following list of strings in Excel:

Example 1: Use VBA to Remove All Occurrences of Character in String (Case-Sensitive)

Suppose that we would like to remove “this” from each string.

We can create the following macro to do so:

Sub RemoveChar()
    Dim i As Integer

    For i = 2 To 8
    Range("B" & i) = Replace(Range("A" & i), "this", "")
    Next i
End Sub

When we run this macro, we receive the following output:

Column B displays each of the strings in column A with each occurrence of “this” removed.

Notice that this macro is case-sensitive.

That is, each occurrence of “this” is removed but each occurrence of “This” is left alone.

Example 2: Use VBA to Remove All Occurrences of Character in String (Case-Insensitive)

Suppose that we would like to remove “this” (regardless of case) from each string.

We can create the following macro to do so:

Sub RemoveChar()
    Dim i As Integer

    For i = 2 To 8
    Range("B" & i) = Replace(LCase(Range("A" & i)), "this", "")
    Next i
End Sub

When we run this macro, we receive the following output:

Column B displays each of the strings in column A with each occurrence of “this” removed.

Notice that this replacement is case-insensitive.

That is, each occurrence of “this” (whether it’s capitalized or not) is removed.

We were able to achieved this by using the LCase method to first convert each string in column A to lowercase before searching for “this” in each string.

Example 3: Use VBA to Remove First N Occurrences of Character in String

Suppose that we would like to remove only the first occurrence of “this” (regardless of case) from each string.

We can create the following macro to do so:

Sub RemoveChar()
    Dim i As Integer

    For i = 2 To 8
    Range("B" & i) = Replace(LCase(Range("A" & i)), "this", "", Count:=1)
    Next i
End Sub

When we run this macro, we receive the following output:

Column B displays each of the strings in column A with only the first occurrence of “this” removed.

Note that we used Count:=1 to remove only the first occurrence of a specific string, but you can replace 1 with any value you’d like to instead remove the first n occurrences of a specific string.

Note: You can find the complete documentation for the VBA Replace method here.

Additional Resources

The following tutorials explain how to perform other common tasks using VBA:

VBA: How to Count Occurrences of Character in String
VBA: How to Check if String Contains Another String
VBA: How to Count Cells with Specific Text

44 / 0 / 0

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

Сообщений: 95

1

Удаление символов из строки

19.01.2012, 12:02. Показов 59450. Ответов 4


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

приведите пожалуйста пример.



0



Апострофф

Заблокирован

19.01.2012, 12:39

2

Visual Basic
1
MsgBox replace("qwerty","y",""),,"Удалили ""y"" из строки ""qwerty"""



1



dnb_dnb

44 / 0 / 0

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

Сообщений: 95

19.01.2012, 13:11

 [ТС]

3

Спасибо! а втавка в строку символов в строку?

я вот знаю, что можно вот так

Visual Basic
1
2
3
4
Dim s as string, s1 as string, s2 as string
s1="сам"
s2="лёт"
s=s1+"o"+s3

и получиться самолёт. а можно с использованием ключевых слов? тоже приведите, пожалуйста, лёгкий пример, как привели с удалением

Добавлено через 12 минут
можете сказать что означают двойные пустые кавычки?

Цитата
Сообщение от Апострофф
Посмотреть сообщение

«y»,»»



0



Апострофф

Заблокирован

19.01.2012, 13:12

4

Visual Basic
1
2
3
4
Dim s(1) as string,ss$
s(0)="сам"
s(1)="лёт"
ss=join(s,"о")

Других путей в VBA я не знаю

Цитата
Сообщение от dnb_dnb
Посмотреть сообщение

что означают двойные пустые кавычки?

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

Цитата
Сообщение от dnb_dnb
Посмотреть сообщение

«y»,»»

— меняем «y» на пустую строку это значит!



1



Dragokas

Эксперт WindowsАвтор FAQ

17993 / 7619 / 890

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

Сообщений: 11,352

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

19.01.2012, 13:25

5

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

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Sub aa()
Dim st As String
Dim Num As Integer
 
st = "Abcdef"
Num = 33
 
'вставить число 33 между левыми 2-мя символами и правыми 4-мя строки "Abcdef"
d = Left(st, 2) & Num & Right(st, 4)
MsgBox d
 
End Sub

При написании программы слева и справа от знака & обязательно ставьте пробелы.



1



Работа с текстом в коде 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):

Пользовательская форма с элементами управления Label и CommandButton

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

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 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


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

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

Ранг: Участник

Сообщений: 73


Репутация:

1

±

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


Excel 2019

[vba]

Код

Dim c as Range
Dim str as String
for each c in selection
str = c.value
If left(str,1) = 7 then
c.value = right(str, len(str)-1)
end if
next

[/vba]
Но если вы вместо цифры захотите убрать, допустим букву а, тогда надо написать = «a», т.е. взят ь в кавычки

Сообщение отредактировал TD_MElecПятница, 19.11.2021, 21:04

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Как удалить символ в начале ячейки excel
  • Как удалить символ в конце ячейки excel
  • Как удалить символ в конце строки excel
  • Как удалить символ в excel формулой
  • Как удалить символ в excel 2010

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии