------ 需求案例------
一次性清除A1:A9单元格区域中不需要的字符。如:-,/,*等字符。
本篇神奇的VBA提供3种思路。
------ 思路1------
Sub 清除字符思路1()
Dim str As String
Dim cell As Range
For Each cell In Range("A1:A9")
str = Replace(Replace(Replace(cell, "/", "-"), "*", "-"), "-", "")
cell = str
Next
End Sub
注意:很遗憾的VBA中的Replace函数不能同时对多种字符集中删除,只能使用嵌套的方式删除!
------ 思路2------
Sub 清除字符思路2()
arr = Array("/", "-", "*") '数组的另一种快捷写法arr = [{"/","-","*"}]
Dim str As String
Dim cell As Range
For Each cell In Range("A1:A9")
str = cell.Text
For Each e In arr
str = Replace(str, e, "")
Next
cell = str
Next
End Sub
注意:思路2跟思路1中的代码其实是换汤不换药,无非是将字符统一放入数组,这样减少Replace的嵌套。 《神奇的VBA》插件对数组有详细的介绍。
------ 思路3------
Sub 清除字符思路3()
Dim RegExp As Object
Dim rng As Range, cell As Range
'此处定义正则表达式
Set RegExp = CreateObject("vbscript.regexp")
RegExp.Pattern = "[/-*]"
RegExp.Global = True
RegExp.IgnoreCase = True
'此处指定查找范围
Set rng = ActiveSheet.Range("A1")
'遍历查找范围内的单元格
For Each cell In rng
Set Matches = RegExp.Execute(cell.Value)
If Matches.Count >= 1 Then
' Set Match = Matches(0)
cell.Value = RegExp.Replace(cell.Value, "#")
End If
Next
Set RegExp = Nothing
End Sub
正则表达式跟字典一样都不属于Excel VBA的自带功能,需要绑定才能使用VB脚本中的正则表达式功能。上面例子中,使用CreateObject绑定正则, 可查阅《神奇的VBA》中的字典方法了解相关功能。我本人不希望职场人多使用正则,更希望职场人有一个规范的表格数据。
------ 结语------
联系客服