Excel vba worksheetfunction trim

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

WorksheetFunction.Trim method (Excel)

vbaxl10.chm137126

vbaxl10.chm137126

excel

Excel.WorksheetFunction.Trim

1e596960-90d8-87f8-9f1f-3a5c9e302e0c

05/25/2019

medium

WorksheetFunction.Trim method (Excel)

Removes all spaces from text except for single spaces between words. Use Trim on text that you have received from another application that may have irregular spacing.

Syntax

expression.Trim (Arg1)

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1 Required String Text — the text from which you want spaces removed.

Return value

String

Remarks

[!IMPORTANT]
The TRIM function in Excel was designed to trim the 7-bit ASCII space character (value 32) from text. In the Unicode character set, there is an additional space character called the nonbreaking space character that has a decimal value of 160. This character is commonly used in webpages as the HTML entity,  . By itself, the Trim function and WorksheetFunction.Trim method don’t remove this nonbreaking space character.

The WorksheetFunction.Trim method in Excel differs from the Trim function in VBA, which removes only leading and trailing spaces.

[!includeSupport and feedback]

In this Article

  • Trim Function
    • Trim Spaces Before and After Text
    • Trim Multiple Spaces Before and After Text
    • VBA Trim will NOT Remove Multiple Spaces Between Words
    • Trim as a Worksheet Function
    • Use Worksheet Trim Function in VBA
    • Difference Between WorksheetFunction.Trim and VBA Trim
    • Use VBA to add Trim Function in a Range
    • LTrim Function
    • RTrim Function
    • Remove all spaces from text

This tutorial will demonstrate how to use the Trim, LTrim, and RTrim VBA functions as well as the Trim worksheet function.

Trim Function

The VBA Trim function removes (“trims”) erroneous spaces before and after strings of text.

Trim Spaces Before and After Text

The VBA Trim function will remove spaces before and after strings of text:

Sub TrimExample_1()
MsgBox Trim(" I love excel ")		
'Result is: "I love excel"

MsgBox Trim(" I love excel")		
'Result is: "I love excel"

MsgBox Trim("I love excel ")		
'Result is: "I love excel"
End Sub

Trim Multiple Spaces Before and After Text

This includes trimming multiple spaces before and after text:

Sub TrimExample_2()
MsgBox Trim("     I love excel          ")		
'Result is: "I love excel"

MsgBox Trim("      I love excel")			
'Result is: "I love excel"

MsgBox Trim("I love excel             ")		
'Result is: "I love excel"
End Sub

VBA Trim will NOT Remove Multiple Spaces Between Words

However, the Trim function will not remove multiple spaces in between words:

Sub TrimExample_3()
MsgBox Trim("     I love    excel          ")		
'Result is: "I love    excel"

MsgBox Trim("      I  love excel")			
'Result is: "I  love excel"

MsgBox Trim("I love        excel             ")		
'Result is: "I love        excel"
End Sub

Trim as a Worksheet Function

However, the Excel Trim worksheet function can be used to remove extra spaces between words:

trim worksheet remove extra spaces

Use Worksheet Trim Function in VBA

To use the Excel Trim Function in VBA, call it by using WorksheetFunction:

Sub TrimExample_4()
Msgbox WorksheetFunction.Trim("     I love    excel          ")	
'Result is: "I love excel"

Msgbox WorksheetFunction.Trim("      I  love excel")		
'Result is: "I love excel"

Msgbox WorksheetFunction.Trim("I love        excel             ")	
'Result is: "I love excel"
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

Difference Between WorksheetFunction.Trim and VBA Trim

This will demonstrate the differences between Trim and WorksheetFunction.Trim:

Sub TrimExample_5()
Msgbox WorksheetFunction.Trim("     I love    excel          ")	
'Result is: "I love excel"
Msgbox Trim("     I love    excel          ")				
'Result is: "I love    excel"

Msgbox WorksheetFunction.Trim("      I  love excel")		
'Result is: "I love excel"
Msgbox Trim("      I  love excel")					
'Result is: "I  love excel"

Msgbox WorksheetFunction.Trim("I love        excel             ")	
'Result is: "I love excel"
Msgbox Trim("I love        excel             ")				
'Result is: "I love        excel"

End Sub

Use VBA to add Trim Function in a Range

The Trim Worksheet function can be added in a Range using property .Formula:

Sub TrimExample_6()
ThisWorkbook.Worksheets("Sheet1").Range("B1").Formula = "=trim(A1)"		
End Sub

LTrim Function

The LTrim function removes spaces only from the left side of the word:

Sub TrimExample_7()
MsgBox LTrim(" I love excel ")			
'Result is: "I love excel "

MsgBox LTrim(" I love excel")			
'Result is: "I love excel"

MsgBox LTrim("I love excel ")			
'Result is: "I love excel "

MsgBox LTrim("   I love   excel   ")		
'Result is: "I love   excel   "

MsgBox LTrim("   I   love excel")			
'Result is: "I   love excel"

MsgBox LTrim("I love    excel   ")			
'Result is: "I love    excel    "
End Sub

VBA Programming | Code Generator does work for you!

RTrim Function

The RTrim function removes spaces only from the right side of the word:

Sub TrimExample_8()
MsgBox RTrim(" I love excel ")			
'Result is: " I love excel"

MsgBox RTrim(" I love excel")			
'Result is: " I love excel"

MsgBox RTrim("I love excel ")			
'Result is: "I love excel"

MsgBox RTrim("   I love   excel   ")		
'Result is: "   I love   excel"

MsgBox RTrim("    I    love excel")		
'Result is: "    I    love excel"

MsgBox RTrim("I    love excel    ")		
'Result is: "I     love excel    "
End Sub

Trim, Ltrim and Rtrim do not remove spaces between words.

Remove all spaces from text

Trim will only remove extra spaces in between words, but to remove all spaces in a string of text, you can use the Replace Function:

Sub ReplaceExample ()
MsgBox Replace("     I love     excel ", " ", "")		
'Result is: "Iloveexcel"
End Sub

Удаление лишних пробелов из строк с помощью кода VBA Excel. Функции LTrim, RTrim, Trim. Встроенная функция рабочего листа и пользовательская функция. Пример.

  • LTrim(строка) — удаление пробелов слева;
  • RTrim(строка) — удаление пробелов справа;
  • Trim(строка) — удаление пробелов слева и справа.

Встроенная функция рабочего листа

Функция VBA Trim удаляет пробелы только по краям строки, не затрагивая двойные, тройные и т.д. пробелы внутри текста. Для удаления всех лишних пробелов следует использовать встроенную функцию Trim рабочего листа Excel.

Синтаксис функции Trim рабочего листа:

WorksheetFunction.Trim(строка)

Пользовательская функция

Можно бороться с лишними пробелами и с помощью пользовательской функции:

Function myTrim(text As String) As String

‘Удаляем пробелы слева и справа строки

  text = Trim(text)

‘Удаляем лишние пробелы внутри строки

    Do While InStr(text, »  «)

      text = Replace(text, »  «, » «)

    Loop

  myTrim = text

End Function

Пример удаления лишних пробелов

Сократим лишние пробелы в одной и той же строке с помощью функции Trim VBA, встроенной функции Trim рабочего листа Excel, пользовательской функции myTrim и сравним результаты.

Sub Primer()

Dim a1 As String

a1 = »  Жили   у     бабуси «

MsgBox Trim(a1) & vbCrLf _

& WorksheetFunction.Trim(a1) _

& vbCrLf & myTrim(a1)

End Sub

Чтобы код примера сработал без ошибок, код пользовательской функции myTrim должен быть добавлен в тот же модуль.

Содержание

  1. Метод WorksheetFunction.Trim (Excel)
  2. Синтаксис
  3. Параметры
  4. Возвращаемое значение
  5. Замечания
  6. Поддержка и обратная связь
  7. How to remove spaces in between text?
  8. 10 Answers 10
  9. VBA Trim, LTrim, and RTrim Functions – Remove Spaces From Text
  10. Trim Function
  11. Trim Spaces Before and After Text
  12. Trim Multiple Spaces Before and After Text
  13. VBA Trim will NOT Remove Multiple Spaces Between Words
  14. Trim as a Worksheet Function
  15. Use Worksheet Trim Function in VBA
  16. VBA Coding Made Easy
  17. Difference Between WorksheetFunction.Trim and VBA Trim
  18. Use VBA to add Trim Function in a Range
  19. LTrim Function
  20. RTrim Function
  21. Remove all spaces from text
  22. VBA Code Examples Add-in
  23. Vba excel сжать пробелы
  24. VBA Excel. Работа с текстом (функции)
  25. Функции для работы с текстом
  26. Ключевые слова для работы с текстом
  27. Примеры
  28. Вывод прямых парных кавычек

Метод WorksheetFunction.Trim (Excel)

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

Синтаксис

expression. Обрезка (Arg1)

Выражение Переменная, представляющая объект WorksheetFunction .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Arg1 Обязательный String Text — текст, из которого нужно удалить пробелы.

Возвращаемое значение

String

Замечания

Функция TRIM в Excel предназначена для обрезки 7-битового символа пространства ASCII (значение 32) от текста. В наборе символов Юникода есть дополнительный символ пробела, который называется неразрывным пробелом, который имеет десятичное значение 160. Этот символ обычно используется на веб-страницах в качестве сущности HTML, . Сама по себе функция Trim и метод WorksheetFunction.Trim не удаляют этот неразрывный пробел.

Метод WorksheetFunction.Trim в Excel отличается от функции Trim в VBA, которая удаляет только начальные и конечные пробелы.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

How to remove spaces in between text?

Why trim is not working in VBA?

It is unable to remove the spaces in between the text.

I need to remove the extra spaces so I found Trim to do it but it is not working while ltrim and rtrim are.

10 Answers 10

Excel Trim will remove all spaces except a single space between words. VBA Trim will remove leading and trailing spaces.

Thank MS for using the same keyword for different functions.

Trim removes extra spaces at start and end, not in the middle of a string.

PS. It’s not the most efficient way to remove spaces. I wouldn’t use on many, very long strings or in a tight loop. It might be suitable for your situation.

I know this question is old but I just found it and thought I’d add what I use to remove multiple spaces in VBA.

When you call Trim() VBA is actually calling Strings.Trim(). This function will only remove leading and trailing spaces. To remove excessive spaces within a string, use

Are all your other functions leaving whitespace behind?

CleanUltra removes all whitespace and non-printable characters including whitespace left behind by other functions!

I hope you find this useful. Any improvements are welcome!

Here’s an example of it’s usage:

Here’s a test I ran to verify that the function actually removed all whitespace. vbNullChar was particularly devious. I had to set the function to remove it first, before the CLEAN and TRIM functions were used to stop them from removing all characters after the vbNullChar .

My related issue was that the last character was a chr(160) — a non-breaking space. So trim(replace(Str,chr(160),»»)) was the solution.

I know this question is old but I just want to share my solution on how to deal and fix with this issue.

Maybe you might wondering why sometimes TRIM function isn’t working, remember that it will only remove spaces and spaces are equivalent to ASCII 32. So if these ASCII 13 or ASCII 10 exists in the Beginning or end of your string value then TRIM function will not work on it.

With this code it works for me, by the way if this might not work on your side then try to check the ASCII of you string value because it might have another invisible special char that might not covered on my code to replace on it, kindly add on it to work.
Please see reference for some invisible special char.

Источник

VBA Trim, LTrim, and RTrim Functions – Remove Spaces From Text

In this Article

This tutorial will demonstrate how to use the Trim, LTrim, and RTrim VBA functions as well as the Trim worksheet function.

Trim Function

The VBA Trim function removes (“trims”) erroneous spaces before and after strings of text.

Trim Spaces Before and After Text

The VBA Trim function will remove spaces before and after strings of text:

Trim Multiple Spaces Before and After Text

This includes trimming multiple spaces before and after text:

VBA Trim will NOT Remove Multiple Spaces Between Words

However, the Trim function will not remove multiple spaces in between words:

Trim as a Worksheet Function

However, the Excel Trim worksheet function can be used to remove extra spaces between words:

Use Worksheet Trim Function in VBA

To use the Excel Trim Function in VBA, call it by using WorksheetFunction:

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!

Difference Between WorksheetFunction.Trim and VBA Trim

This will demonstrate the differences between Trim and WorksheetFunction.Trim:

Use VBA to add Trim Function in a Range

The Trim Worksheet function can be added in a Range using property .Formula:

LTrim Function

The LTrim function removes spaces only from the left side of the word:

RTrim Function

The RTrim function removes spaces only from the right side of the word:

Trim, Ltrim and Rtrim do not remove spaces between words.

Remove all spaces from text

Trim will only remove extra spaces in between words, but to remove all spaces in a string of text, you can use the Replace Function:

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Vba excel сжать пробелы

= Мир MS Excel/MS Word: «СЖАТЬ_ПРОБЕЛЫ» — Мир MS Excel

Войти через uID

Войти через uID

Модератор форума: _Boroda_, китин

Мир MS Excel » Вопросы и решения » Excel и другие приложения » Word » MS Word: «СЖАТЬ_ПРОБЕЛЫ» (Аналог функции листа MS Excel «СЖАТЬПРОБЕЛЫ»)

MS Word: «СЖАТЬ_ПРОБЕЛЫ»

Alex_ST Дата: Вторник, 20.12.2011, 14:48 | Сообщение № 1


С уважением,
Алексей
MS Excel 2003 — the best.

808 Дата: Пятница, 03.02.2012, 10:42 | Сообщение № 2

Да, отличный макрос, но когда у меня еще небыло ни интернета ни минимальных познаний в VBA я пользовался простым, довольно эффективным хотя и не таким удобным способом.

Crtl + F > Вкладка «Заменить» > В строке «Найти» ставил два пробела, в строке «Заменить на» один пробел и кликал по кнопке «Заменить все» столько раз, сколько требовалось чтобы убрать все множественные пробелы.

Да, отличный макрос, но когда у меня еще небыло ни интернета ни минимальных познаний в VBA я пользовался простым, довольно эффективным хотя и не таким удобным способом.

Crtl + F > Вкладка «Заменить» > В строке «Найти» ставил два пробела, в строке «Заменить на» один пробел и кликал по кнопке «Заменить все» столько раз, сколько требовалось чтобы убрать все множественные пробелы. 808

Сообщение Да, отличный макрос, но когда у меня еще небыло ни интернета ни минимальных познаний в VBA я пользовался простым, довольно эффективным хотя и не таким удобным способом.

Crtl + F > Вкладка «Заменить» > В строке «Найти» ставил два пробела, в строке «Заменить на» один пробел и кликал по кнопке «Заменить все» столько раз, сколько требовалось чтобы убрать все множественные пробелы. Автор — 808
Дата добавления — 03.02.2012 в 10:42

Источник

VBA Excel. Работа с текстом (функции)

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

Источник

Читайте также:  Как настроить герцовку монитора asus

Adblock
detector

Excel already has a TRIM worksheet function that you can use to get rid of leading, trailing, and extra spaces in between words/strings.

There is a TRIM function in VBA as well (and it does exactly the same thing – remove extra spaces).

Why do we need a TRIM function in VBA too?

Fair question!

While you can work with the inbuilt TRIM function in Excel worksheets to get rid of spaces. in some cases, you may need to do this using VBA.

This could be as a part of a bigger code.

Syntax of the VBA TRIM function

TRIM(String)

‘String’ is the argument that can be a text string or a variable that holds a text string.

Let’s learn how to use the VBA TRIM function with a couple of examples.

Example 1 – Showing Result in a message box

Suppose you have the following text in cell A1

Excel VBA Trim Function - Examples 1 Data

Note that there are spaces before and after the sentence.

The below code would take this sentence, and show the result after trimming the extra spaces

Sub TrimExample1()
MsgBox Trim(Range("A1"))
End Sub

VBA Trim Function code result

There is one important thing to know when using the TRIM function in VBA –  it will only remove the leading and trailing spaces. It will not remove the extra spaces in between words (which the in-built TRIM function in the worksheet does).

For example, suppose you have the following text in cell A1 (with extra spaces in between words):

VBA TRIM Function - Extra spaces in between words

If I use the above VBA code, it will show a message box as shown below:

MessageBox with extra spacesAs you can see in the message box result, the extra spaces between words are not removed by the VBA TRIM function.

Then what’s the alternative?

If you want to remove leading, trailing, as well as double spaces in between words, it’s better to use the following code:

Sub TrimExample1()
MsgBox WorksheetFunction.Trim(Range("A1"))
End Sub

The above code uses the worksheet TRIM function (instead of using the TRIM function in VBA).

Note: VBA Trim function does not remove the non-whitespace characters – such as newlines (vbNewLinevbCrLf) etc.

Example 2 – Quickly Remove Leading and Trailing Spaces from a Range of Cells

Suppose you have a data set as shown below where there are leading and trailing spaces:

VBA TRIM Example 2 Dataset

You can use the below code to instantly clean this data and remove all the leading and trailing spaces:

Sub TrimExample1()
Dim Rng As Range
Set Rng = Selection
For Each Cell In Rng
Cell.Value = Trim(Cell)
Next Cell
End Sub

The above code goes through all the cells in the selection and removes the leading and trailing spaces.

Clean Data with VBA TRIM Function

You May Also Like the Following Excel/VBA Tutorials:

  • 10 Ways to Clean Data in Excel.
  • Excel VBA Split Function.
  • Excel VBA InStr Function.
  • VBA LCase Function.
  • VBA UCase Function.
  • Creating a User Defined Function (UDF) in Excel VBA.

Понравилась статья? Поделить с друзьями:
  • Excel vba thisworkbook sheets
  • Excel vba worksheetfunction max
  • Excel vba thisworkbook saved
  • Excel vba worksheet события
  • Excel vba thisworkbook range