正則表達式在Excel VBA中的應用
感
謝
感謝每一個朋友的關注與支持,感謝所有的不離不棄,一路同行!
關
注
導讀
前兩天分享了一篇關於VBA與正則表達式的文章,裡面寫了如何利用VBA與正則表達式去除字元串中除中文之外的其他字元,只保留中文。
這兩天有朋友問我如果要只保留數字或只保留字母該怎麼辦?所以今天村長再來補充一下其他正則表達式在VBA中的應用。
按ALT+F11彈出VBE窗口,然後新建模塊,如下圖:
只保留中文的代碼如下:
Function ZW(i As String) As String
Dim a As Object
Set a = CreateObject("VBSCRIPT.REGEXP")
a.Pattern = "[^u4e00-u9fa5]"
a.IgnoreCase = True
a.Global = True
ZW = a.Replace(i, "")
Set a = Nothing
End Function
只保留數字的代碼如下:
Function SZ(i As String) As String
Dim a As Object
Set a = CreateObject("VBSCRIPT.REGEXP")
a.Pattern = "[^0-9]"
a.IgnoreCase = True
a.Global = True
SZ = a.Replace(i, "")
Set a = Nothing
End Function
只保留字母的代碼如下:
Function ZM(i As String) As String
Dim a As Object
Set a = CreateObject("VBSCRIPT.REGEXP")
a.Pattern = "[^A-Z^a-z]"
a.IgnoreCase = True
a.Global = True
ZM = a.Replace(i, "")
Set a = Nothing
End Function
只保留數字和字母的代碼如下:
Function SZZM(i As String) As String
Dim a As Object
Set a = CreateObject("VBSCRIPT.REGEXP")
a.Pattern = "[^A-Z^a-z^0-9]"
a.IgnoreCase = True
a.Global = True
SZZM = a.Replace(i, "")
Set a = Nothing
End Function
保存完代碼之後我們回到表格裡面,在單元格輸入我們剛才寫的自定義函數,如下圖:
GIF/1K
堅持!堅持!再堅持!
致各位親
未
完
待
續
每日一歌
羽泉《冷酷到底》
TAG:我的Excel |