用VBA做function,不知道有什么问题

假设我有一个条目列的条目,例如四年级的例子。 我只需要有数值。

Function CleanCode(entry) As Integer If entry Like "[4]" Then entry = 4 End Function 

为什么不这个function呢?

首先,要清理一个以数字字符开始的string,你可以使用“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 

使用正则expression式来高效地清理string。 要清理A1的string,可以在B1input

=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