美文网首页想法简友广场
13.Excel VBA使用正则表达式

13.Excel VBA使用正则表达式

作者: 赵明嗯 | 来源:发表于2020-07-04 13:34 被阅读0次

正则表达式是一种跨语言的字符串处理机制,就像数学运算符一样,是自成体系的。在Excel VBA中使用正则表达式的方式也很简单。

Sub 矩形1_Click()
Dim rg As Range
Dim re As Object
Set re = CreateObject("vbscript.regexp")
With re
.Global = True
.IgnoreCase = True
.Pattern = "([A-Z]\d{1,2}(?=\+))|(^[A-Z]\d{1,2}$)"
End With
Set rg = ActiveSheet.Range("A1:A8")
For Each cell In rg
    If re.test(cell.Value) Then
        'cell.Offset(0, 1) = re.Replace(cell.Value,"aaaa" )
        'cell.Offset(0, 1) = re.Execute(cell.Value)(0)
        cell.Offset(0, 1) = re.Replace(cell.Value, ActiveSheet.Range(re.Execute(cell.Value)(0)).Value)
        Set mat = re.Execute(cell.Value)
        If mat.Count > 1 Then
        cell.Offset(0, 2) = re.Execute(cell.Value)(1)
        End If
    End If
Next
End Sub

不得不说VB真是一种微软下功夫简化的编程语言,虽然在专业程序员层面显得鸡肋,但对轻度编程爱好者来说还是比较好用的一种工具。不同的工具对应不同的人,解决不同层面的问题。
这里需要通过CreateObject("vbscript.regexp")来创建一个正则表达式对象。.Global = True表示可以匹配多个;.Pattern = "([A-Z]\d{1,2}(?=+))|(^[A-Z]\d{1,2}$)"使我们的正则表达式; re.Replace(cell.Value,"aaaa" )是将匹配到的字符串替换成我们需要替换的字符串"aaaa";Execute返回MatchCollection对象,mat.Count 表示该对象的成员个数,如果匹配到了两组字符串,即cell.Value中有两组字符串符合我们的正则表达式,则返回的MatchCollection对象就有两个成员,分别用re.Execute(cell.Value)(0),re.Execute(cell.Value)(1)来引用。

相关文章

网友评论

    本文标题:13.Excel VBA使用正则表达式

    本文链接:https://www.haomeiwen.com/subject/ailuqktx.html