Excel VBA
Excel vba 自定义函数使用正则表达式提取字符串中的数值
2017-09-16 16:38:28

前面我们讲解过提取字符串中的数值的方法。用函数即可简单提取。

下面再讲一下如何用正则表达式 来提取字符串中符合条件的字符。

如下图所示:

从一个单元格中提取出连续出现的数字, 并且用空格分割开

操作步骤:

  1. 打开VBE界面操作界面,菜单栏上中选择插入,插入模块

  2. 编写以下自定义函数,保存即可

  3. Function REFIND(str, re)     Dim Reg As New RegExp     With Reg         .Global = True         .Pattern = re         Set matchs = .Execute(str)         For Each Match In matchs             y = y & " " & Match         Next     End With '    MsgBox y     REFIND = y End Function

  4.  调用函数,单元格内输入 =REFIND(A3,"\d{2,}") 

   注意:因为用到正则表达式,需要引用 Microsoft VBScript Regular Expressions 5.5