Requirement:
The user has a custom function that was created to extract integers from a simple 11 character string that was alphanumeric with a hyphen.
The user needs to modify or create a new custom function that can extract integers (with hyphens in some instances). The new string is variable in length and the integers the user needs to extract are on the left side of a vertical slash (vertical bar).
The custom function the user is currently using is posted below:
Function GetNum(MyInput As String) Dim i As Integer Dim j As Integer Dim NumOnly As String 'Count total strings of Input For i = Len(MyInput) To 1 Step -1 If IsNumeric(Mid(MyInput, i, 1)) Then j = j + 1 NumOnly = Mid(MyInput, i, 1) & NumOnly End If If j = 1 Then NumOnly = CInt(Mid(NumOnly, 1, 1)) Next i GetNum = NumOnly End Function
Here is an example of the old string and new string:
Old String: ABC-1234567
New string 1: 1234567-99 | TEXT MORETEXT EXTENDEDTEXT - 23.8 XX YYYY 16:9
New string 2: 1234567 | BLAH BLAH EXTENDEDBLAH XYZ 123
https://www.ozgrid.com/forum/forum/help-forums/excel-vba-macros/1202952-custom-function-coding
Solution:
To keep the hyphen there are 2 options.
If you expect characters other than numbers and hyphens to the left of the vertical pipe symbol then this should work:
Function ExtractNumA(MyInput As String) As String Dim j As Integer, k As Integer Dim c As String ExtractNumA = "" j = InStr(MyInput, "|") If j = 0 Then Exit Function For k = 1 To j - 1 c = Mid(MyInput, k, 1) If IsNumeric(c) Or c = "-" Then ExtractNumA = ExtractNumA & c Next End Function
If there are only numbers and hyphens to the left of the vertical pipe symbol then this should also work and would be quicker:
Function ExtractNumB(MyInput As String) As String Dim j As Integer, k As Integer Dim c As String ExtractNumB = "" j = InStr(MyInput, "|") If j = 0 Then Exit Function ExtractNumB = Left(MyInput, j - 1) End Function
In both cases all hyphen characters will be returned eg, if there is more than one
Obtained from the OzGrid Help Forum.
Solution provided by gijsmo.
See also: Index to Excel VBA Code and Index to Excel Freebies and Lesson 1 - Excel Fundamentals and Index to how to… providing a range of solutions and Index to new resources and reference sheets
See also:
How to custom filter using a macro |
How to create VBA return that will return customised results when comparing two worksheets |
How to use COUNTIF to see if a customer is a repeat customer |
How to obtain a true or false statement if a customer is a repeat customer |
Click here to visit our Free 24/7 Excel/VBA Help Forum where there are thousands of posts you can get information from, or you can join the Forum and post your own questions.