How about this one. Note the use of Worksheetfunction.Trim, which removes several spaces that Application.Trim does not.
Option Explicit Dim oRegex As Object Sub test() Dim dirtyString As String dirtyString = " This*&(*&^% is_ The&^%&^%><><.,.,.,';';'; String " Debug.Print cleanStr(dirtyString) End Sub Function cleanStr(ByVal dirtyString As String) As String If oRegex Is Nothing Then Set oRegex = CreateObject("vbscript.regexp") With oRegex .Global = True 'Allow AZ, az, 0-9, a space and a hyphen - .Pattern = "[^A-Za-z0-9 -]" cleanStr = .Replace(dirtyString, vbNullString) End With cleanStr = WorksheetFunction.Trim(cleanStr) End Function
source share