0

Say I have a column of entries where the entries are grades, say for this example 4th grade. I only need to have the numerical value.

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

why doesn't this function do it?

2
  • What is the value of the Variant "entry"? Commented Jan 20, 2013 at 3:31
  • entry would just be a cell with data in it like either 4, 4th grade, or 4th. Commented Jan 20, 2013 at 3:41

2 Answers 2

3

Firstly, to "clean" a string the starts with a numeric character, you use the "Val(" function. I think you are also expecting the "entry" parameter to be changed by the CleanCode function, however you must explicitly return the value.

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

We can call this function from another function to see how it operates:

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you! Exactly what I was trying to do.
You are quite welcome. As a sidebar, you can also use "If entry Like "4th*" Then CleanCode = 4" to achieve the same result. Val( is going to be faster.
What could I do if the entry begins with grade? Like grade 4? The Val function doesn't help much here.
For this you will need to use Like "4" (that is Asterisk4Asterik)
0

Use a to efficiently clean your string. To clean a string in A1, in B1 you could enter

=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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.