如何解决用vba替换范围内的任何字母[A-Z]
我有一个自由文本字段,其中包含文本和不同长度的数字。我需要用“ x”替换列中的任何字母。我已经成功地使用'rng.replace'替换了特定文本,但需要包含任何字母[A-Z]
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
我无法获得正确的语法以“ What”匹配任意字母A-Z
任何帮助将不胜感激。我有一个有效的循环,但是,它非常慢,使整个过程停滞不前。我已经将上面的rng.replace用来加快除“文本”替换之外的所有内容的处理过程。
解决方法
请尝试下一个功能,
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
要在一定范围内使用它,请尝试以下代码:
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
请进行测试并发送一些反馈...
,有很多方法可以使猫看起来很皮
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
,
如果性能是一个问题,通常通过检查字符串数组的字节值来更快地做到这一点。像这样:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。