使用VBA来实现功能,不确定是什么问题

时间:2013-01-20 03:28:04

标签: excel vba

假设我有一列条目,其中的条目是成绩,比如说这个例子是4年级。我只需要有数值。

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

为什么这个功能没有呢?

2 个答案:

答案 0 :(得分:3)

首先,要使用数字字符“清理”字符串,请使用“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

答案 1 :(得分:0)

使用有效清理字符串。要清除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