简体   繁体   中英

Excel Extract nth first words from a string

I'd like to create a function in vba to extract the first nth words from a string and to look like this

ExtractWords(affected_text, delimiter, number_of_words_to_extract)

I tried a solution but it only extracts the first two words.

Function FirstWords(myStr As Variant, delimiter,words_to_extract) As Variant
  FirstWords = Left(myStr, InStr(InStr(1, myStr, delimiter) + 1, myStr, delimiter, vbTextCompare) - 1)
End Function

Any ideas? Thanks

Use Split() function. It returns array of String , split using the delimiter and limit of words you specify.

Dim Result As Variant
Result = Split("Alice,Bob,Chuck,Dave", ",") 'Result: {"Alice,"Bob","Chuck","Dave"}
Result = Split("Alice,Bob,Chuck,Dave", ",", 2) 'Result: {"Alice,"Bob"}

@Taosique's answer using Split is excellent, but if you want the result returned as a string you can do the following:

Function FirstWords(myStr As String, delimiter As String, words_to_extract As Long) As Variant
    Dim i As Long, k As Long
    For i = 1 To Len(myStr)
        If Mid(myStr, i, 1) = delimiter Then
            k = k + 1
            If k = words_to_extract Then
                FirstWords = Mid(myStr, 1, i)
                Exit Function
            End If
        End If
    Next I

    'if you get to here -- trouble
    'unless the delimiter count is words_to_extract - 1
    If k = words_to_extract - 1 Then
        FirstWords = myStr
    Else
        FirstWords = CVErr(xlErrValue)
    End If    End Function

Sub test()
    Debug.Print FirstWords("This is a test. I hope it works", " ", 4)
    Debug.Print FirstWords("This is a test. I hope it works", " ", 10)
End Sub

When test is run it first displays the string "This is a test." then prints an error condition.

Much the same effect as the above can be achieved by first splitting the string using Split and then rejoining it using Join . A subtle difference is the behavior if there are less than words_to_extract words. The Split then Join approach will return the whole string. The above code treats this as an error condition and, if used as a UDF worksheet function, will display #VALUE! in any cell that contains it.

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