我正在 Excel 2010 中编写一个宏,以便删除列的多个单元格中的换行符。
实际上,我必须在单元格中搜索 5 个案例。
我列举如下:
如您所见,2 和 3 非常相似,所以我认为正则表达式可能类似于
[a-zA-Z0-9]\n
但我不知道...首先,如果只添加\n 搜索换行符是否正确,然后,如何搜索空格。检测到正则表达式后,我认为可以用一个 .Replace(Text,"regexp","regexp ")
来解决。其中结尾空格来自“char”+“”形式所以基本上我的问题是,这种模式的正则表达式是什么?
在第 5 种情况下,我如何搜索行终止符,以便它不会尝试在段落的最后一个点之后搜索换行符。
我可以将 Chr(10) 用于换行,将 Chr(32) 用于空格吗?
顺便说一句,我一直在关注这些引用资料:
How to use RegExp
VBA Split strings
最佳答案
此模式将查找任何字母数字字符 .
, 或 ,
后跟可选的空格,然后是换行符并将其替换为匹配的结束字符,后跟一个空格。
Dim re
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "([\w.,])\s*\n"
strText = re.Replace(strText, "$1 ")
测试的输出。忽略括号。他们只是在那里展示空间。
[the end.] = [the end.]
[the end.\n] = [the end. ]
[the end. \n] = [the end. ]
[the end. \n] = [the end. ]
[the end,] = [the end,]
[the end,\n] = [the end, ]
[the end, \n] = [the end, ]
[the end, \n] = [the end, ]
[the end] = [the end]
[the end\n] = [the end ]
[the end \n] = [the end ]
[the end \n] = [the end ]
关于regex - 如何在 VBA 宏中使用正则表达式解析 Excel 单元格字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31970873/