This is a very fast way to do it using Regular Expressions
and a VBA Array
. It uses early binding so you will need to add a VBA reference to "Microsoft VBScript Regular Expressions 5.5"
Sub DemoRegExr()
Dim RegEx As New RegExp
Dim arr As Variant
Dim i As Long
With ActiveSheet
' Range "E1:E3"
arr = .Range(.Cells(1, 5), .Cells(3, 5)).Value2
With RegEx
.IgnoreCase = True
.Global = True
.Pattern = "[^A-Z ]"
For i = LBound(arr) To UBound(arr)
If .test(arr(i, 1)) Then
' Using WorksheetFunction.Trim to remove double spacing
arr(i, 1) = WorksheetFunction.Trim(.Replace(arr(i, 1), vbNullString))
End If
Next i
End With
' Range "C1:C3"
.Cells(1, 3).Resize(UBound(arr)).Value2 = arr
End With
End Sub
This could also be written as a Function
Function cleanString(str As Variant) As String
Dim RegEx As New RegExp
' Default value
cleanString = str
With RegEx
.IgnoreCase = True
.Global = True
.Pattern = "[^A-Z ]"
If .test(str) Then
cleanString = WorksheetFunction.Trim(.Replace(str, vbNullString))
End If
End With
End Function
And called as
Sub DemoArr()
Dim arr As Variant
Dim i As Long
With ActiveSheet
' Range "A1:A3"
arr = .Range(.Cells(1, 5), .Cells(3, 5)).Value2
For i = LBound(arr) To UBound(arr)
' Using WorksheetFunction.Trim to remove double spacing
arr(i, 1) = cleanString(arr(i, 1))
Next i
.Cells(1, 3).Resize(UBound(arr)).Value2 = arr
End With
End Sub