假设我有一列条目,其中条目是等级,例如这个例子是四年级。我只需要有数值。
Function CleanCode(entry) As Integer
If entry Like "[4]" Then entry = 4
End Function
为什么这个功能不做呢?
首先,要“清理”以数字字符开头的字符串,请使用“Val(”函数。我认为您还期望 CleanCode 函数更改“entry”参数,但是您必须显式返回该值.
Function CleanCode(entry) As Integer
entry = Val(entry)
If entry Like "[4]" Then
entry = 4
Else
entry = -1
End If
CleanCode = entry
End Function
我们可以从另一个函数调用这个函数,看看它是如何运行的:
Sub CallCC()
Dim entry As Variant
entry = "9th"
Dim Result As Integer
Result = CleanCode(entry)
MsgBox "Result = " & Result
'Result is -1
entry = "4th grade"
Result = CleanCode(entry)
MsgBox "Result = " & Result
' Result = 4
End Sub
使用正则表达式有效地清理您的字符串。要清除字符串 in A1
,B1
您可以输入
=CleanString(A1)
Sub Tester()
MsgBox CleanString("3d1fgd4g1dg5d9gdg")
End Sub
Function CleanString(strIn As String) As String
Dim objRegex
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Global = True
.Pattern = "[^\d]+"
CleanString = .Replace(strIn, vbNullString)
End With
End Function