Home » excel » excel – VBA formula removing everything after second space

excel – VBA formula removing everything after second space

Posted by: admin May 14, 2020 Leave a comment


I was trying to copy from column D to column E first two words of each row but still can not find where the error is….

Range("E1:E" & lLastRow).Formula = "=LEFT(D1,FIND("" "",D1,FIND("" "",D1)+1)-1)"
How to&Answers:

Another option, instead of using a Formula, you can use the Split function.


Dim i As Long, LastRow As Long
Dim WordsArr As Variant

' loop through rows
For i = 1 To LastRow
    WordsArr = Split(Range("D" & i).Value, " ")  ' use Split and space to read cell words to array

    If UBound(WordsArr) >= 1 Then ' make sure the cell contents is at least 2 words
        Range("E" & i).Value = WordsArr(0) & " " & WordsArr(1) ' insert only the first 2 words

    Else ' in case there are less than 2 words
        ' do someting....

    End If
Next i

End Sub


Try this instead …

Range("E1:E" & lLastRow).FormulaR1C1 = "=LEFT(RC[-1],FIND("" "",RC[-1],FIND("" "",RC[-1])+1)-1)"

I find using R1C1 better for those sort of operations, especially given you want your references to be dynamic, not absolute.

Alternatively, add the formula you had normally and simply fill down.