excel - Get the nth word or the last word if apporopriate -
i using great little piece of code pull names out of 1 cell , separate them separate cells. number of names varies , such need automate as possible.
i using following macro:
function get_word(text_string string, nth_word) string dim lwordcount long application.worksheetfunction lwordcount = len(text_string) - len(.substitute(text_string, " ", "")) + 1 if isnumeric(nth_word) nth_word = nth_word - 1 get_word = mid(mid(mid(.substitute(text_string, " ", "^", nth_word), 1, 256), _ .find("^", .substitute(text_string, " ", "^", nth_word)), 256), 2, _ .find(" ", mid(mid(.substitute(text_string, " ", "^", nth_word), 1, 256), _ .find("^", .substitute(text_string, " ", "^", nth_word)), 256)) - 2) elseif nth_word = "first" get_word = left(text_string, .find(" ", text_string) - 1) elseif nth_word = "last" get_word = mid(.substitute(text_string, " ", "^", len(text_string) - _ len(.substitute(text_string, " ", ""))), .find("^", .substitute(text_string, " ", "^", _ len(text_string) - len(.substitute(text_string, " ", "")))) + 1, 256) end if end end function
i can specify word goes column (e.g. get_word(j2, 4)
).
unfortunately have hit snag, if specific word last word in cell not extracted unless specify ( e.g. get_word(j2, "last")
). making tricky , mean have go through cells individually.
what love know if there way change vba script above in excel can specify want 4th word or "last" word if case.
you try this:
function get_word(text_string string, nth_word) string dim vwords dim lwordcount long vwords = split(text_string, " ") lwordcount = ubound(vwords) + 1 if isnumeric(nth_word) if nth_word < 1 nth_word = 1 if nth_word > lwordcount nth_word = lwordcount get_word = vwords(nth_word - 1) elseif nth_word = "first" get_word = vwords(0) elseif nth_word = "last" get_word = vwords(lwordcount - 1) end if end function
if want nothing if pass large value:
function get_word(text_string string, nth_word) string dim vwords dim lwordcount long vwords = split(text_string, " ") lwordcount = ubound(vwords) + 1 if isnumeric(nth_word) if nth_word > lwordcount get_word = "" else if nth_word < 1 nth_word = 1 get_word = vwords(nth_word - 1) end if elseif nth_word = "first" get_word = vwords(0) elseif nth_word = "last" get_word = vwords(lwordcount - 1) end if end function
you can still use =get_word(a1,"last") if want, if use =get_word(a1,3) , there 2 words, you'll empty string back.
Comments
Post a Comment