简体   繁体   English

可以找到如何在VBA中使用正则表达式替换

[英]Can find how to use replace with regex in VBA

I have a table in Excel and one of its columns contains string of the type: 125j, 0j, 12j, etc. 我在Excel中有一张表,它的列之一包含类型的字符串:125j,0j,12j等。

I want the value of the cells (in this column) to be replace by the numbers (ie I want to drop the "j") using the VBA. 我希望使用VBA将单元格(在此列中)的值替换为数字(即,我想删除“ j”)。 Here is what I have: 这是我所拥有的:

Dim reg As Object
Set reg = CreateObject("VBScript.RegExp")
reg.IgnoreCase = True
reg.Pattern = "^[0-9]+"

If reg.test(Cells(i, 4).Value) Then
    Cells(i, 4).Value = reg.Execute(Cells(i, 4).Value)
End If

But it doesn't work, do anyone knows either how to crrect it or to obtain the same result from another command? 但这是行不通的,有人知道如何压缩它或从另一个命令中获得相同的结果吗?

Thank you 谢谢

The result of the .Execute method is a MatchCollection object. .Execute方法的结果是MatchCollection对象。 You can use that explicitly: 您可以明确地使用它:

Dim reg As Object
Dim allMatches As Object

Set reg = CreateObject("VBScript.RegExp")
reg.IgnoreCase = True
reg.Pattern = "^[0-9]+"

If reg.test(cells(i, 4).Value) Then
    Set allMatches = reg.Execute(cells(i, 4).Value)
    cells(i, 4).Value = allMatches(0)
End If

Or implicitly: 或隐式地:

    cells(i, 4).Value = reg.Execute(cells(i, 4).Value)(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 bash 中使用正则表达式变量进行查找和替换命令? - How can I use a regex variable for a find and replace command in bash? 如何在Excel中使用VBA和RegEx替换数据? - How to use VBA and RegEx in Excel to replace data? 如何使用“用正则表达式查找和替换”来查找参数并将其替换为参数 - How can I use Find and Replace with REGEX to find a parameter and replace it with the parameter 我如何找到在单词 VBA 中使用正则表达式并将每个匹配项替换为匹配项中的 substring? - How can i find using regex in word VBA and replace each match with a substring from the match? 如何使用正则表达式替换此字符串 - How can I use Regex to replace this string 如何在 VBA 中使用正则表达式替换第 n 次出现? - How can I replace the nth occurence using regex in VBA? 如何在VBA excel宏中进行正则表达式搜索和替换? - How can I do a regex search and replace in a VBA excel macro? 如何使用正则表达式查找和替换在花括号前插入缺失的空格? - How can I use regex find-and-replace to insert missing spaces before curly braces? 使用VBA将RegEx字符串替换为Word中的超链接 - Use VBA to replace RegEx strings with hyperlinks in Word 如何在PhpStorm的“查找和替换”中使用RegEx标志? - How to use RegEx flags in PhpStorm's “Find and Replace”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM