简体   繁体   English

用 vba 替换范围内的任何字母 [AZ]

[英]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".我需要用“x”替换列中的任何字母。 I have had success with replacing specific text using 'rng.replace' but need to include any letter [AZ]我已成功使用 'rng.replace' 替换特定文本,但需要包含任何字母 [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我无法获得“什么”的正确语法来匹配任何和所有字母 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.我已经使用上述 rng.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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