宏跳过A列并删除小写字母

时间:2014-02-07 17:31:28

标签: regex excel excel-vba vba

  • A栏中,我有一个句子列表
  • B-Z列中,我的字符串包含数字,后跟大写和小写字母。

,例如

  

45ABc

以下宏删除整个工作表中的所有小写字母 - 不要让它删除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

2 个答案:

答案 0 :(得分:1)

试试这个:

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中替换的值,您也可以使用下一个代码:

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

答案 1 :(得分:1)

我添加了以下代码:

  1. 修复您的模式以删除您想要删除的内容 - 即a-z - 而不是您要保留的内容(目前A-Z-_但可能更大)。
  2. 使用更快的数组而不是范围循环。

    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 = "[a-z]+"
        .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