|
楼主 |
发表于 2015-8-7 12:24
|
显示全部楼层
本帖最后由 autumnalRain 于 2015-8-9 14:55 编辑
一个例子:利用正则表达式的环视结构求字符串中的数量并进行求和。请大家也帮助解答下,红色部分究竟起了什么作用?
Sub 字符串取值()
Dim Lastcell, Rng, Regx, Cell, Mat
Set Lastcell = Cells(Rows.Count, "B").End(xlUp)
Set Rng = Range([B2], Lastcell)
Set Regx = CreateObject("VBSCRIPT.REGEXP")
With Regx
.Global = True
.Pattern = "\d+(?=张$)"
End With
For Each Cell In Rng
Set Mat = Regx.Execute(Cell)
For Each M In Mat
n = n + 1
Cells(n + 1, "C") = Regx.Replace(M, "")'请大家看下这句REPLACE的作用在哪里?
Sum = Sum + Cells(n + 1, "C")
Next
Next
MsgBox "累计数量" & Sum & "张"
End Sub
另一种方法:
- Sub 字符串取值()
- Dim Lastcell, Rng, Regx, Cell, Mat
- Set Lastcell = Cells(Rows.Count, "B").End(xlUp)
- Set Rng = Range([B2], Lastcell)
- Set Regx = CreateObject("VBSCRIPT.REGEXP")
- With Regx
- .Global = True
- .Pattern = "\d+(?=张$)"
- End With
- For Each Cell In Rng
- Set Mat = Regx.Execute(Cell)
- For Each m In Mat
- n = n + 1
- Cells(n + 1, "C") = m
- Sum = CLng(m) + Sum
- Next
- Next
- MsgBox "累计数量" & Sum & "张"
- End Sub
复制代码
|
|