Excel - 在VBA中使用正则表达式拆分单元格,保留分隔符

时间:2017-08-17 14:19:32

标签: regex excel vba excel-vba

我在Excel中有一行单元格,遵循以下语法:

randomtext VALUES( randomnumber randomtext

我有一个VB脚本,可以使用正则表达式分割文本:

Public Function SplitRe(text As String, pattern As String, Optional ignorecase As Boolean) As String()
  Static re As Object
  If re Is Nothing Then
    Set re = CreateObject("VBScript.RegExp")
    re.Global = True
    re.MultiLine = True
  End If
  re.ignorecase = ignorecase
  re.pattern = pattern
  SplitRe = Strings.Split(re.Replace(text, vbNullChar), vbNullChar)
End Function

我使用的分隔符:(VALUES)+(\s+)+(.)+\d+(,)

这导致文本被拆分为:

randomtext

我想要实现的是在脚本找到分隔符后拆分文本,创建它:

randomtext VALUES( randomnumber

但我无法找到一种方法来正确扩充我的脚本。有人看到了解决方案吗?

1 个答案:

答案 0 :(得分:1)

没有正则表达式既不分裂:

更快:

 Left(text, InStrRev(text,",")) 'Truncate string after last comma

更安全(假设VALUES (没有出现在randomtext}中:

 Left(text, InStr(InStr(text,"VALUES ("),text,",")) 'Truncate string after comma which is after "VALUE ("
相关问题