简体   繁体   中英

Replace any letter [A-Z] in a range with vba

I have a free text field that contains both text and numbers of varying lengths. I need to replace any letter in the column with "x". I have had success with replacing specific text using 'rng.replace' but need to include any letter [AZ]

Dim rng as Range, lastRow As Long

lastRow = ActiveSheet.Range("A" & Rows.Count).Emd(xlUp).Row
Set rng = ActiveSheet.Range("E2:E" & lastRow)

rng.replace What:=[A-Z], Replacement:="x", MatchCase:=False

I cannot get the correct syntax for "What" to match any and all letters AZ

Any help would be appreciated. I have a loop that works, however, it is very slow and stalling my overall process too much. I have worked the above rng.replace into speeding up the process for everything except this "text" replace.

Try the next function, please:

Function removeLetters(strX As String) As String
  With CreateObject("vbscript.regexp")
    .Pattern = "[^0-9]" 'pattern to replace everything except numbers
    .Global = True
    removeLetters = .Replace(strX, "X")
  End With
End Function

To use it for a range, please try the next code:

Sub testRngRemoveLetters()
  Dim sh As Worksheet, rng As Range, C As Range, usedCol As Long, lastRow As Long
  
  Set sh = ActiveSheet ' use here your sheet
  usedCol = 2          'column B:B. Use the column number you need
  lastRow = sh.cells(Rows.count, usedCol).End(xlUp).Row 'last row on the chosen column
  'building the range to be processed:
  Set rng = sh.Range(sh.cells(2, usedCol), sh.cells(lastRow, usedCol))

  'Use the above function to replace everything else then numbers:
  For Each C In rng
     C.value = removeLetters(C.value)
  Next
End Sub

Please, test it and send some feedback...

Plenty of ways to skin a cat it seems.

Dim Number As Long
Dim Letter As String
Set Rng = Range("A1")
For Number = 1 To 28
    Letter = Split(Cells(1, Number).Address, "$")(1)
    Rng.Replace What:=(Letter), Replacement:="x", MatchCase:=False
    Number = Range(Letter & 1).Column
Next

If performance is an issue, it's usually faster to do this by checking the byte values of the string array. Something like this:

Public Function ReplaceAlphas(txt As String) As String
    Dim i As Long, a As Long
    Dim b() As Byte
    
    b = txt
    For i = 0 To UBound(b) Step 2
        a = b(i)
        If (a >= 65 And a <= 90) Or (a >= 97 And a <= 122) Then
            b(i) = 120
        End If
    Next
    ReplaceAlphas = b
    
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM