在 Excel 中使用正則表達式進行查找與替換

在 Excel 中,使用 Alt+F11 快捷鍵打開 VBA 項目窗口,在左側的工做表名稱上點右鍵,選擇查看代碼,便可出出現右側的代碼編輯窗口正則表達式

image

在代碼窗口中輸入如下代碼:spa

Private Sub RegExp_Replace()

    Dim RegExp As Object
    Dim SearchRange As Range, Cell As Range
    
    '此處定義正則表達式
    Set RegExp = CreateObject("vbscript.regexp")
    RegExp.Pattern = "[0-9]{5}"
     
    '此處指定查找範圍
    Set SearchRange = ActiveSheet.Range("A1:A99")
    
    '遍歷查找範圍內的單元格
    For Each Cell In SearchRange
        Set Matches = RegExp.Execute(Cell.Value)
        If Matches.Count >= 1 Then
            Set Match = Matches(0)
            Cell.Value = RegExp.Replace(Cell.Value, "")
        End If
    Next

End Sub

根據實際須要替換相應參數,點擊 image 運行便可獲得效果。code

相關文章
相關標籤/搜索