2014-02-07 42 views
1
  • A專欄中,我有句
  • B-Z列的列表,我有一個字符串包含數字後跟字母大寫和小寫。

宏跳過列A和剝離了小寫字母

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 
+0

你的模式應該是準確的,你要刪除的東西 - 跟不上。看到我的帖子下面。 – brettdj

回答

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用於固定'B:Z'部分,但我認爲OP的模式也需要解決。 – brettdj

1

我已經添加代碼:

  1. 修復你爸ttern刪除你想要什麼直接刪除 - 即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 
    
+1

+1你說得對,陣列快得多:) –