Убрать пробел vba excel

Удаление лишних пробелов из строк с помощью кода 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 должен быть добавлен в тот же модуль.

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

Are all your other functions leaving whitespace behind?

Get CleanUltra!

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!

Function CleanUltra( _
       ByVal stringToClean As String, _
       Optional ByVal removeSpacesBetweenWords As Boolean = False) _
        As String
' Removes non-printable characters and whitespace from a string


' Remove the 1 character vbNullChar. This must be done first
'  if the string contains vbNullChar
    stringToClean = Replace(stringToClean, vbNullChar, vbNullString)

    ' Remove non-printable characters.
    stringToClean = Application.Clean(stringToClean)

    ' Remove all spaces except single spaces between words
    stringToClean = Application.Trim(stringToClean)

    If removeSpacesBetweenWords = True Then _
       stringToClean = Replace(stringToClean, " ", vbNullString)

    CleanUltra = stringToClean
End Function

Here’s an example of it’s usage:

Sub Example()
    Dim myVar As String
    myVar = " abc d e  "

    MsgBox CleanUltra(myVar)
End Sub

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.

Sub Example()
    Dim whitespaceSample As String
    Dim myVar As String

' Examples of various types of whitespace
'  (vbNullChar is particularly devious!)
    whitespaceSample = vbNewLine & _
                       vbCrLf & _
                       vbVerticalTab & _
                       vbFormFeed & _
                       vbCr & _
                       vbLf & _
                       vbNullChar

    myVar = "     1234" & _
            whitespaceSample & _
            "     56      " & _
            "789     "

    Debug.Print "ORIGINAL"
    Debug.Print myVar
    Debug.Print "Character Count: " & Len(myVar)


    Debug.Print
    Debug.Print "CLEANED, Option FALSE"


    Debug.Print CleanUltra(myVar)
    Debug.Print CleanUltra(myVar, False)
    '   Both of these perform the same action.  If the optional parameter to
    '   remove spaces between words is left blank it defaults to FALSE.
    '   Whitespace is removed but spaces between words are preserved.
    Debug.Print "Character Count: " & Len(CleanUltra(myVar))


    Debug.Print
    Debug.Print "CLEANED, Option TRUE"

    Debug.Print CleanUltra(myVar, True)
    '   Optional parameter to remove spaces between words is set to TRUE.
    '   Whitespace and all spaces between words are removed.
    Debug.Print "Character Count: " & Len(CleanUltra(myVar, True))

End Sub

 

Andrey

Пользователь

Сообщений: 41
Регистрация: 01.01.1970

как на VBA будет выглядить функция СЖПРОБЕЛЫ() ?

 

Haken

Пользователь

Сообщений: 495
Регистрация: 09.01.2013

Trim()  
причем и как функция листа, а так же есть и функция VBA, если надо в коде переменную «сжать»

 

аналог функции СЖПРОБЕЛЫ в VBA — не TRIM(» текст   текст  «), а  
application.WorksheetFunction.Trim(» текст   текст  «)  

  Последнюю можно также записать как  
WorksheetFunction.Trim(» текст   текст  «)  
и  
application.Trim(» текст   текст  «)  

    TRIM убирает пробелы только справа и слева,  
application.Trim уберет также повторяющиеся проблы внутри текста.

 

Andrey

Пользователь

Сообщений: 41
Регистрация: 01.01.1970

Но не получается почемуто..  
ячейка водержит «cxczxczxc zczxcz          zxczxczxc           zczxc»  
вот кусок кода :  

  cell = Trim(cell)  

  но ничего не происходит….

 

Hugo

Пользователь

Сообщений: 23257
Регистрация: 22.12.2012

Добавлю — Trim() уберёт только пробелы в начале и в конце, а двойные внутри оставит. А вот в VBA Excel при Application.WorksheetFunction.Trim(Ячейка.Value) —  будут удаляться лидирующие и финиширующие пробелы, а также многократные пробелы между словами (исползуется стандартная функция СЖПРОБЕЛЫ)

 

Hugo

Пользователь

Сообщений: 23257
Регистрация: 22.12.2012

{quote}{login=Andrey}{date=03.04.2010 07:17}{thema=}{post}Но не получается почемуто..  
ячейка водержит «cxczxczxc zczxcz          zxczxczxc           zczxc»  
вот кусок кода :  

  cell = Trim(cell)  

  но ничего не происходит….{/post}{/quote}  

  Так трим убирает только в начале и в конце — а там пробелов нет.  
cell = Application.WorksheetFunction.Trim(cell) используйте.

 

Hugo

Пользователь

Сообщений: 23257
Регистрация: 22.12.2012

Вообще-то автор давал нормальную строку, с множественными пробелами внутри, но движок форума при выводе обрезал. Но я при цитировании их видел — можете попробовать цитнуть :) (интересный эффект — в цитате есть пробелы, при выводе — нет).

 

Andrey

Пользователь

Сообщений: 41
Регистрация: 01.01.1970

Объесняю немного подробнее,что хочется получить..  
Есть диапазон ячеек,  в котором есть ячейки с содержанием «лишних»  пробелов.  
Вот нужен макрос, который бы «убивал» лишние пробелы ( по подобию результата действия функции Excel = СЖПРОБЕЛЫ() )  

  До макроса было :  
«Вася__Петя____Коля»  
После макроса :  
«Вася_Петя_Коля»  

  «_» — это пробелы (т.к. двойные пробелы движек форума «съедает»)

 

Афтар, выдели диапазон ячеек на листе и запусти этот код  

  Sub DelSpaces()  
Dim iCell As Range  
   If MsgBox(«Удалить лишние пробелы в выделенном диапазоне?», vbQuestion + vbYesNo, «Чистка пробелов») = vbNo Then Exit Sub  
   For Each iCell In Selection.Cells  
       iCell = Application.Trim(iCell)  
   Next  
   MsgBox «Лишние пробелы в указанном диапазоне удалены!», 64, «Конец»  
End Sub  

  и не мучай людей по пустякам )))

 

{quote}{login=}{date=03.04.2010 10:59}{thema=}{post}Афтар, выдели диапазон ячеек на листе и запусти этот код  

  Sub DelSpaces()  
Dim iCell As Range  
   If MsgBox(«Удалить лишние пробелы в выделенном диапазоне?», vbQuestion + vbYesNo, «Чистка пробелов») = vbNo Then Exit Sub  
   For Each iCell In Selection.Cells  
       iCell = Application.Trim(iCell)  
   Next  
   MsgBox «Лишние пробелы в указанном диапазоне удалены!», 64, «Конец»  
End Sub  

  и не мучай людей по пустякам ))){/post}{/quote}  
Вот так все же поэффективнее будет :-)  

  Sub test()  
   With Selection  
       .Value = Application.Trim(.Value)  
   End With  
End Sub

 

)) Кирилл как всегда на высоте ) Спасибо, буду знать )

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

KL, Ваше появление на форуме — подарок к празднику? Рад видеть (слышать? читать?) :)

 

{quote}{login=vikttur}{date=04.04.2010 01:24}{thema=}{post}KL, Ваше появление на форуме — подарок к празднику? Рад видеть (слышать? читать?) :){/post}{/quote}  
vikttur,  
Спасибо на добром слове. Я периодически почитываю форум, но времени отвечать почти нет. Да и потом в моем понимании здесь нет недостатка в квалифицированных ответах :-)

 

KuklP

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

{quote}{login=KL}{date=04.04.2010 04:36}{thema=Re: }{post}{quote}{login=}{date=03.04.2010 10:59}{thema=}{post}Афтар, выдели диапазон ячеек на листе и запусти этот код  

  Sub DelSpaces()  
Dim iCell As Range  
   If MsgBox(«Удалить лишние пробелы в выделенном диапазоне?», vbQuestion + vbYesNo, «Чистка пробелов») = vbNo Then Exit Sub  
   For Each iCell In Selection.Cells  
       iCell = Application.Trim(iCell)  
   Next  
   MsgBox «Лишние пробелы в указанном диапазоне удалены!», 64, «Конец»  
End Sub  

  и не мучай людей по пустякам ))){/post}{/quote}  
Вот так все же поэффективнее будет :-)  

  Sub test()  
   With Selection  
       .Value = Application.Trim(.Value)  
   End With  
End Sub{/post}{/quote}  
Улет! Я бы не додумался.:-(

Я сам — дурнее всякого примера! …

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

А у меня что-то так работать не хочет…  
Давно написанный для себя макрос:  
Sub Trim_with_Cycle()   ‘ применить функцию СЖПРОБЕЛЫ к ячейкам выделенного диапазона  
  Dim rRange As Range, rCell As Range  
  Application.ScreenUpdating = False  

    Set rRange = Intersect(Selection, ActiveSheet.UsedRange)  
  For Each rCell In rRange  
     rCell.Value = Application.WorksheetFunction.Trim(rCell.Value)  
  Next  

    Application.ScreenUpdating = True  
End Sub  

  работает отлично, а точно такой же, но по методу, предложенному KL (все ячейки диапазона сразу, а не циклом):  

  Sub Trim_with_Range()   ‘ применить функцию СЖПРОБЕЛЫ к ячейкам выделенного диапазона  
  Dim rRange As Range  
  Application.ScreenUpdating = False  

    Set rRange = Intersect(Selection, ActiveSheet.UsedRange)  
  rRange.Value = Application.WorksheetFunction.Trim(rRange.Value)  

    Application.ScreenUpdating = True  
End Sub  

  работать не хочет. Говорит, что «Несоответствие типа» (ошибка 13)

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Я так сразу и пробовал.    
Если убрать .WorksheetFunction и написать просто:  
rRange.Value = Application.Trim(rRange.Value)  
то выдаётся «Ошибка, определяемая приложением или объектом» (ошибка 1004)

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Dophin

Пользователь

Сообщений: 2684
Регистрация: 01.01.1970

Sub Trim_with_Range() ‘ применить функцию СЖПРОБЕЛЫ к ячейкам выделенного диапазона  
Dim rRange As Range  
Set rRange = Intersect(Selection, ActiveSheet.UsedRange)  
rRange.Value = Application.Trim(rRange.Value)  
End Sub  

  так у меня работает, с функцией листа не работает.

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Подрихтовываю свой макрос, удаляющий лишние пробелы в ячейках.  
Чтобы не портились формулы и форматы даты/времени решил всё-таки отказаться от обработки целиком диапазона:  
rRange.Value = Application.Trim(rRange.Value),  
а ввести проверку каждой ячейки: не формула ли в ней, не дата ли, не время ли?  

  С формулой и датой всё ясно:  

  Sub Trim_By_Formula() ‘ применить функцию СЖПРОБЕЛЫ к ячейкам выделенного диапазона  
  Dim rRange As Range, rCell As Range  
  Application.ScreenUpdating = False  
  Set rRange = Intersect(Selection, ActiveSheet.UsedRange)  
  For Each rCell In rRange  
     If rCell.EntireRow.Height > 0 _  
        And Not (rCell.HasFormula) _  
        And Not IsDate(rCell) Then  
        rCell.Value = Application.WorksheetFunction.Trim(rCell.Value)  
     End If  
  Next  
  Application.ScreenUpdating = True  
End Sub  

  А вот как проверить не время ли в ячеёке?  
Свойство IsDate(rCell) вернёт ИСТИНУ при любом из форматов даты в ячейке.  
А как быть с разными форматами времени? Ведь аналогичного свойства IsTime(rCell) — в VBA нет…

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Юрий М

Модератор

Сообщений: 60588
Регистрация: 14.09.2012

Контакты см. в профиле

Но ведь время — это дата.

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

Это Вы так думаете, а Ёксель — нет.  
Попробуйте ввести в одну ячейку, например, 1.1.10 (автоматически преобразуется после ввода в дату 01.01.2010), а в другую — 10:00 (преобразуется после ввода во время 10:00:00).  
А потом попробуйте применить к ячейкам мой макрос из предыдущего поста.  
Или просто напишите  
Private Sub Worksheet_SelectionChange(ByVal Target As Range)  
MsgBox IsDate(Target)  
End Sub  
«Покликайте» по ячейкам и сами увидите, что IsDate будет True только при дате в ячейке, а при времени — False

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

 

Юрий М

Модератор

Сообщений: 60588
Регистрация: 14.09.2012

Контакты см. в профиле

А вот так корректно будет?  
Sub TestTimeFormat()  
Dim x As String  
x = ActiveCell.NumberFormat  
If x Like «*» & «:» & «*» Then MsgBox «Время»  
End Sub

 

Юрий М

Модератор

Сообщений: 60588
Регистрация: 14.09.2012

Контакты см. в профиле

Нет: если в ячейке формат дата + время, то тоже сработает. Тогда так:  
Sub TestTimeFormat()  
Dim x As String  
x = ActiveCell.NumberFormat  
If Len(x) < 9 And x Like «*» & «:» & «*» Then MsgBox «Только время»  
End Sub

 

Alex_ST

Пользователь

Сообщений: 2746
Регистрация: 22.12.2012

На лицо ужасный, добрый внутри

#23

12.05.2010 13:15:43

Мужики, а что быстрее будет работать в цикле:  
If Target.NumberFormat Like «*» & «:» & «*» Then …  
или  
If InStr(1, Target.NumberFormat, «h:mm», vbTextCompare) > 0 Then …

С уважением, Алексей (ИМХО: Excel-2003 — THE BEST!!!)
<#0>

VBA TRIM FUNCTION

Excel VBA Trim Function

Excel VBA Trim Function is used for removing the extra spaces from any cell or text and gives us the output which has a standard in terms of required spaces. VBA Trim function works exactly as the Excel Trim function and Trim function also removes the extra spaces in 3 ways;

  1. Spaces from the starting of the text.
  2. Spaces from the end of the text.
  3. Spaces from the middle of the text if more than 1 extra space is seen.

This mostly happens when we download data from some server, data warehouse or while incorrectly inserting the extra spaces manually. Even though we can easily see the spaces at the middle of the text, but spaces at the beginning and end of text cannot be seen easily until and unless we go to edit mode of that specific cell. This can be done by VBA Marco.

How to Use Excel VBA Trim Function?

We will discuss how to use VBA Trim Function by using some examples.

You can download this VBA Trim Function Excel Template here – VBA Trim Function Excel Template

VBA Trim Function – Example #1

Here we have 3 cells in the below screenshot.

Excel Data

And each cell has some spaces associated with them. Cell A1 has spaces at the end.

Cell A1

Cell A2 has spaces at the beginning of the text.

Cell A2

And cell A3 has space in between the text which is highlighted in the below screenshot.

Cell A3

For trimming these cells we will use Excel VBA. For that, press Alt + F11 keys together or under Developer tab click on Visual Basic as shown below.

VBA Option

This will take us to Visual Basic coding window. Now go to the Insert menu from VBA window and select Module as shown below.

Insert Module

This will create a new Module where we will write a code for trimming. Below are the steps for creating and writing trimming code:

  • First, choose a variable and define a range. Here we have selected the variable “A”. This variable can be anything.
  • As our data set has already some text or object then we need to set the range for it. And for that, we will use “Selection”. It will automatically select the data in the present sheet.

Code:

Sub Trim_Data()
   
    Dim A As Range
    
    Set A = Selection

End Sub

Selection

  • For selecting each filled cell of the sheet “For Each” is the function And Value function is used for selecting the value with Trim(Cell) selection.

Code:

Sub Trim_Data()

    Dim A As Range

    Set A = Selection

    For Each cell In A
    cell.Value = WorksheetFunction.Trim(cell)
    Next

End Sub

Trim Function

By this, we complete the coding work for creating macro through VBA Trim. Now let’s apply the created code into some tab. For this go to Insert Menu and under Illustrations select Shapes.

Shapes Option

From that Shapes option, create any shape using shape formats and styles.

Shape Formats

Here we have created a rectangular box and named it TRIM as shown below.

Trim Box

Now click on the Design Mode in Developer menu and right-click on the created box or shape. From the right-click, menu list select Assign Macro to link our created code as shown below.

Assign Macro

We will get the Assign Marco window, from there select already created macro code, here we have Trim_Data and then click on OK.

How to Assign Macro

Now select the data and click on the TRIM button. We will get the selected trimmed and spaces that were not required are now removed as shown below.

 Result after Clicking on Trim Button

VBA Trim Function – Example #2

VBA Coding shown above can be written in one more way. In the above example, we only trimmed the selected data. In this we will insert the function in the message box as well it will show once the data is trimmed.

For this, we will use the same data which we used in example 1. Follow the same steps, go to the Developer tab and click on Visual Basic.

VBA Option

Once we do that, we will get the Visual Basic window. Now open a fresh Module and start coding on that page.

Now consider the same code which we have written in example-1. But here for printing a message box with the text we will insert some text.

Code:

Sub Trim_Data2()

    Dim A As Range

    Set A = Selection

    For Each cell In A
    cell.Value = WorksheetFunction.Trim(cell)

    Dim B As String

    B = Trim("Trimming Done")

    MsgBox B

    Next

End Sub

Trimming Function Message

Once we are done with writing the code, close the Visual Basic windows.

Now go to the Developer tab again and click on Insert menu as shown below. We will get a drop-down menu of different button shapes as shown below.

Insert Button

Now select any of the button shapes and draw it on anywhere on your workbook. From the list of created macros select the required option. Here we have selected Trim_Data2 which we created for this example and then click OK.

Assign Macro to Button

After that, we will get the button created on the screen.

Assign Macro to Renamed Button

We can name the button as per function which we will be performing. Let’s name it TRIM as per function. Now right click on the created TRIM button and select Assign Marco. Once we do that we will get the window Assign Marco as shown below. Now select the required macro and click OK.

Assign Macro to Button

By this, our trim coding will get assigned to TRIM Button. Now for testing select the data first and then click on this TRIM Button.

Trim Message Box

As we can see above, here our data got trimmed and we can see the message as well of “Trimming Done”.

Pros of Excel VBA Trim Function

  • We can trim huge sets of data in one shot without checking the number of extra spaces the cells have.
  • Coding of trimming function is also quite small.
  • There are very less or no chances that any extra space will get spared.

Things To Remember

  • Always save the file as Macro-Enabled Worksheet. By doing this, we can use assigned macro multiple time.
  • Compile the code before assigning it to any button.
  • There are 2 different ways are shown for creating a button and both can be used as per individuals need or wish.
  • Consider writing VBA Code as shown in example-2 which will give the message as well.

Recommended Articles

This has been a guide to Excel VBA Trim. Here we discussed how to use VBA Trim Function to remove spaces in Excel along with some practical examples and downloadable excel template. You can also go through our other suggested articles–

  1. VBA Function
  2. VBA VLOOKUP
  3. VBA Get Cell Value
  4. VBA XML

Понравилась статья? Поделить с друзьями:
  • Убрать предупреждение при объединении ячеек в excel
  • Убрать последнюю цифру в числе excel
  • Убрать последний символ строки excel
  • Убрать последние цифры в ячейке excel
  • Убрать подчеркивание текста в excel