macros跳过A列并去掉小写字母
- 在
A
栏中,我有一个句子列表 - 在
BZ
列中,string中包含数字,后面跟着大写字母和小写字母。
如
45ABc
下面的macros将整个工作表中的所有小写字母去掉 – 不希望它去掉A列中的任何字母。请帮忙。
Sub RegExReplace() Dim RegEx As Object Set RegEx = CreateObject("VBScript.RegExp") RegEx.Global = True RegEx.Pattern = "[^A-Z0-9_-]" For Each objCell In ActiveSheet.UsedRange.Cells objCell.Value = RegEx.Replace(objCell.Value, "") Next End Sub
试试这个:
Sub RegExReplace() Dim objCell As Range Dim RegEx As Object Set RegEx = CreateObject("VBScript.RegExp") RegEx.Global = True RegEx.Pattern = "[^A-Z0-9_-]" For Each objCell In ActiveSheet.UsedRange.Cells If objCell.Column<>1 Then objCell.Value = RegEx.Replace(objCell.Value, "") Next End Sub
或者如果您知道只应在列B:Z
replace的值,则还可以使用下一个代码:
Sub RegExReplace() Dim rng As Range, objCell As Range Dim RegEx As Object Set RegEx = CreateObject("VBScript.RegExp") RegEx.Global = True RegEx.Pattern = "[^A-Z0-9_-]" With ActiveSheet Set rng = Application.Intersect(.UsedRange, .Range("B:Z")) End With If Not rng Is Nothing Then For Each objCell In rng objCell.Value = RegEx.Replace(objCell.Value, "") Next End If End Sub
我已经添加了以下代码:
- 修复你的模式,以删除你想要直接删除的东西 – 即
az
– 而不是你想保留的东西(目前AZ-_
但可能会更大)。 -
使用更快的数组而不是范围循环。
Sub objRegexReplace() Dim rng1 As Range Dim objRegex As Object Dim X Dim lngRow As Long Dim lngCol As Long Set rng1 = Application.Intersect(ActiveSheet.UsedRange, ActiveSheet.Range("B:Z")) X = rng1.Value2 If rng1.Cells.Count > 1 Then Set objRegex = CreateObject("VBScript.Regexp") With objRegex .Global = True .Pattern = "[az]+" .ignorecase = False For lngRow = 1 To UBound(X, 1) For lngCol = 1 To UBound(X, 2) X(lngRow, lngCol) = .Replace(X(lngRow, lngCol), vbNullString) Next Next rng1.Value2 = X End With Else MsgBox "No range to work on", vbCritical End If End Sub