2024年4月27日发(作者:)

[ExcelVBA]提取字符串中数字、中文、英文字符的自定义函数

(修正版)

展开全文

本文链接

/blog/static/4/

分类:Excel VBA 编程

请根据具体要求编辑宏代码应用。

修正版:

Sub Sample()

' by oicu# 2009/7/31

' 数据在第一列(A列),结果放在第二列(B列)之后

' 提取数字时设置不带小数点的数值格式防止出现1.21314E+12这种科学记数法

' 设置列宽自动适应数据长度

' 修正全字母时提取得到数字0

' 英文标点不会提取出来的

Dim i As Integer

For i = 1 To (Columns(1))

' 默认为提取数字

Cells(i, 2).NumberFormatLocal = "0_ "

Cells(i, 2).Value = GetNum(Cells(i, 1).Value)

' Cells(i, 2).Value = GetNum(Cells(i, 1).Value, 0)

' 提取中文及中文标点

Cells(i, 3).Value = GetNum(Cells(i, 1).Value, 1)

' 提取字母

Cells(i, 4).Value = GetNum(Cells(i, 1).Value, 2)

Next i

Columns("B:B").t

Columns("C:C").t

Columns("D:D").t

End Sub

Function GetNum(Srg As String, Optional n As Integer = False)

Dim i As Integer

Dim s, MyString As String

Dim Bol As Boolean

For i = 1 To Len(Srg)

s = Mid(Srg, i, 1)

Select Case n

Case 0

Bol = s Like "#"

' Bol = s Like "[0-9]"

Case 1

Bol = Asc(s) < 0

' 中文为负数,不要用AscB或者AscW

Case 2

Bol = s Like "[a-zA-Z]"

' zA之间不要带半角逗号

Case Else

Exit Function

End Select

If Bol Then MyString = MyString & s

Next i

If MyString <> "" Then _

GetNum = IIf(n = 1 Or n = 2, MyString, Val(MyString))

End Function

Excel中用函数提取字符串中的数字的方法请看另一篇日志:

/blog/static/1232119363/