Search
Close this search box.

VBA – Trim String


The Trim function in VBA is used to remove all leading and trailing spaces from a string.

Syntax:

Trim(string)

Parameter:

 

  • string: The string from which you want to remove leading and trailing spaces.


Return Value:

  • String: Returns the same string without any leading or trailing spaces.

 

Example

				
					Dim str1 As String
Dim trimmedStr As String

str1 = "   Hello, World!   " 
trimmedStr = Trim(str1) 

' trimmedStr will be "Hello, World!"
				
			

Use Cases:

  • Data Cleaning:
    • Removing extra spaces from user input.
    • Preparing data for database entry or processing.
  • String Comparisons:
    • Ensuring accurate string comparisons by removing any leading or trailing spaces that might affect the result.
  • Data Formatting:
    • Removing unnecessary spaces from the beginning and end of text fields in reports or forms.

       

      Key Considerations:

      • Trim removes only leading and trailing spaces. It does not remove spaces within the string itself.