vba code to remove leading and trailing spaces code example
Example 1: excel vba remove leading or trailing spaces in an entire column of data
Function CleanMAX(r As Range)
CleanMAX = Replace("trim(clean(substitute(|,char(160),"" "")))", "|", r.Address)
If r.Cells.Count > 1 Then CleanMAX = "index(" & CleanMAX & ",)"
CleanMAX = Evaluate(CleanMAX)
End Function
v = CleanMAX([a1])
v = CleanMAX([a1:z10])
Example 2: vba remove leading blank space in string
Option Explicit
Function trimWhiteSpace(s As String) As String
Dim RE As Object: Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.MultiLine = True
.Pattern = "^\s*(\S.*\S)\s*"
trimWhiteSpace = .Replace(s, "$1")
End With
End Function