做项目过程中需要对某一列字段进行添加“【】”将字段包裹起来,因此上网查了EXCEL的正则匹配如何使用,在此记录一下,防止忘记。

打开文件一定要选择EXCEL打开,WPS目前没有发现该功能(平时使用也很少)。下面步入正题,打开EXCEL文件后。按住ALT+F11,右键文件选择“查看代码”,输入代码:

EXCEL利用正则匹配去替换内容

 代码如下:

Private Sub RegExp_Replace()

    Dim RegExp As Object
    Dim SearchRange As Range, Cell As Range
    
    '此处定义正则表达式
    Set RegExp = CreateObject("vbscript.regexp")
    RegExp.Pattern = "^"
     
    '此处指定查找范围
    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

点击EXCEL利用正则匹配去替换内容执行代码,即可完成所需功能。

前后结果对比:

EXCEL利用正则匹配去替换内容                EXCEL利用正则匹配去替换内容

相关文章:

  • 2022-12-23
  • 2021-07-26
  • 2021-09-03
  • 2022-01-24
  • 2021-11-04
  • 2022-01-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-29
  • 2021-06-20
  • 2022-12-23
  • 2022-12-23
  • 2021-08-22
  • 2022-01-26
  • 2022-12-23
相关资源
相似解决方案