简体   繁体   中英

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.

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. 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM