简体   繁体   中英

Extract A String Between Two Characters In Excel

theStr = "KT150"

Characters count is always 5 in total. I want to make sure that there is 3 numbers in theStr. How would I achieve this in Excel VBA?

You do not need VBA to get the number of digits in a string, but here is one way to count them:

Public Function KountNumbers(r As Range) As Long
    Dim i As Long, t As String

    t = r.Text
    For i = 1 To Len(t)
        If Mid(t, i, 1) Like "[0-9]" Then KountNumbers = KountNumbers + 1
    Next i
End Function

for example:

在此处输入图片说明

Without VBA try this:

=SUMPRODUCT(LEN(A1)-LEN(SUBSTITUTE(A1,{0,1,2,3,4,5,6,7,8,9},"")))

to get the number of numeric digits.

This should help:

Function onlyDigits(s As String) As String
    ' Variables needed (remember to use "option explicit").   '
    Dim retval As String    ' This is the return string.      '
    Dim i As Integer        ' Counter for character position. '

    ' Initialise return string to empty                       '
    retval = ""

    ' For every character in input string, copy digits to     '
    '   return string.                                        '
    For i = 1 To Len(s)
        If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
            retval = retval + Mid(s, i, 1)
        End If
    Next

    ' Then return the return string.                          '
    onlyDigits = retval
End Function

Example:

Dim myStr as String
myStr = onlyDigits ("3d1fgd4g1dg5d9gdg")
MsgBox (myStr)

Will return (in a message box):

314159

*Code is exact copy of this SO answer

Your question is a little lacking in detail, but how about:

Sub test()

    Debug.Print containsXnumbers("KT150", 3)

End Sub

Function containsXnumbers(sInput As String, xNumbers As Long) As Boolean

    Dim x As Long
    Dim numCount As Long

    For x = 1 To Len(sInput)
        If IsNumeric(Mid(sInput, x, 1)) Then numCount = numCount + 1
    Next x

    If numCount = xNumbers Then containsXnumbers = True

End Function

try with the below formula

Assume that your data are in A1. Apply the below formula in B1

=IF(AND(LEN(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"1",""),"2",""),"3",""),"4",""),"5",""),"6",""),"7",""),"8",""),"9",""),"0",""))=2,LEN(A1)=5),"3 character numerals","No 3 numerals found")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM