Extracting first word from a string in vba, where the nth string is a single word

436 Views Asked by At

I am able to extract the first word from a string, using VBA, by searching for the space between two words. The code is like this:

Sub ConnectionTable()

Dim j As Integer
Dim i As Integer


For j = 6 To 8

    For i = 2 To 8
        If (InStr(1, ThisWorkbook.Worksheets("RcmCauses").Cells(j, 5).Value, Left(ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 5).Value, InStr(ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 5), " ")))) And (ThisWorkbook.Worksheets("RcmCauses").Cells(j, 2).Value Like "* hoofdmotor *") And (ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 2).Value Like "* hoofdmotor *") Then
            ThisWorkbook.Worksheets("RcmCauses").Cells(j, 6).Value = 1 - 1 + j
            ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 6).Value = ThisWorkbook.Worksheets("RcmCauses").Cells(j, 6).Value
            j = j + 1
            i = 2
            
        ElseIf (InStr(1, ThisWorkbook.Worksheets("RcmCauses").Cells(j, 5).Value, Left(ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 5).Value, InStr(ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 5), " ")))) And (ThisWorkbook.Worksheets("RcmCauses").Cells(j, 2).Value Like "* noodmotor *") And (ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 2).Value Like "* noodmotor *") Then
            ThisWorkbook.Worksheets("RcmCauses").Cells(j, 6).Value = 1 - 1 + j
            ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 6).Value = ThisWorkbook.Worksheets("RcmCauses").Cells(j, 6).Value
            j = j + 1
            i = 2
         
        ElseIf (InStr(1, ThisWorkbook.Worksheets("RcmCauses").Cells(j, 5).Value, Left(ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 5).Value, InStr(1, ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 5), " ")))) Then
            ThisWorkbook.Worksheets("RcmCauses").Cells(j, 6).Value = 1 - 1 + j
            ThisWorkbook.Worksheets("RcmCausesWantij").Cells(i, 6).Value = ThisWorkbook.Worksheets("RcmCauses").Cells(j, 6).Value
            j = j + 1
            i = 1
        Else
            ThisWorkbook.Worksheets("RcmCauses").Cells(j, 6).Value = 1 - 1 + j

        End If
        
    Next i
   
Next j
End Sub

Everthing goes well until I come accross a string that only consist of one word, so no space can be found (see picture below). What happens is that the second elseif-statement suddenly becomes true, while it supposed to be false. How can I still extract one word from a string that only contains one word while other strings contain multiple words?

Screenshot of strings

0

There are 0 best solutions below