我正在尝试使用Regex在Excel中拆分字符串: 这是要匹配的字符串:
Powerunit: .75HP
Powerunit: 1HP
预期结果:
Powerunit:
.75
HP
到目前为止我写的代码:
Sub simpleRegex()
Dim strPattern As String: strPattern = "(Powerunit: )(\.?[0-9]{1,2})(HP)"
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As Range
Sheet4.Activate
Set Myrange = ActiveSheet.Range("b1:b6")
Dim c As Range
If strPattern <> "" Then
For Each c In Myrange.Cells
strInput = c.value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
ActiveSheet.Range("G" & c.Row).value = regEx.Replace(strInput, "$1")
ActiveSheet.Range("H" & c.Row).value = regEx.Replace(strInput, "$2")
ActiveSheet.Range("I" & c.Row).value = regEx.Replace(strInput, "$3")
Else
MsgBox ("Not matched")
End If
Next
End If
End Sub
我只对HP值感兴趣(即.75或1);但我似乎无法得到它。 它只打印“ $ 1 ”字面而不是值。
但如果我像这样添加$ 2 $ 3,则会显示“ .75HP ”:
ActiveSheet.Range("H" & c.Row).value = regEx.Replace(strInput, "$2 $3")
答案 0 :(得分:1)
正如@ A.S.H所指出的那样,我的目的地单元格格式为&#39; Currency&#39 ;; 它在改变之后起作用了