J
jgarbis
I have an excel sheet and I need to clean out all non-letter
characters and keep only a-z, how do I do that?
characters and keep only a-z, how do I do that?
Gord Dibben said:This macro will delete all but A-Z in cells with constants.
What do you want done with formulas? Convert to values and strip also?
If so, make revision as noted at code lines below.
Public Sub StripAllButAZs() ....
On Error Resume Next
Set myRange = Range(ActiveCell.Address & "," & Selection.Address) _
.SpecialCells(xlCellTypeConstants) ....
If myRange Is Nothing Then Exit Sub
If Not myRange Is Nothing Then
For Each cell In myRange
myStr = cell.text
For i = 1 To Len(myStr)
If (Asc(UCase(Mid(myStr, i, 1))) < 65) Or _
(Asc(UCase(Mid(myStr, i, 1))) > 90) Then
myStr = Left(myStr, i - 1) & " " & Mid(myStr, i + 1)
End If
Next i
cell.Value = Application.Trim(myStr)
Next cell
End If
With Application
.Calculation = xlAutomatic
.ScreenUpdating = True
End With
End Sub
....Harlan Grove said:For Excel 2000 and later, it'd be more efficient to use
Dim c As String * 1
:
For i = 1 To Len(myStr)
c = Mid$(myStr, i, 1)
If c Like "[!A-Za-z]" Then myStr = Replace(myStr, c, "", i)
Next i
If myStr Like "*[!A-Za-z]*" Then
For i = 1 To Len(myStr)
c = Mid$(myStr, i, 1)
If c Like "[!A-Za-z]" Then myStr = Replace(myStr, c, "", i)
Next i
End If
I believe repeated executions of Replace might not be as efficient
as multiple "string stuffing" followed by a single execution of
the Replace function...
If myStr Like "*[!A-Za-z]*" Then
For i = 1 To Len(myStr)
If Mid$(myStr, i, 1) Like "[!A-Za-z]" Then _
Mid$(myStr, i, 1) = " "
Next
myStr = Replace(myStr, " ", "")
End If
where I chose to use a blank space as the string stuffing
character (but any non-alpha character would do).
nonalphas were random with few if any multiple instances in any cell,
then your approach may be faster. But if there were multiple instances
of particular characters, getting rid of all of them (and shortening
the string in the process) could be faster.
Also, you don't need to insert " " for instances of " " in mystr, so
make the second Like pattern "[!A-Za-z ]".