vbams-wordword-2007

Clear / Empty Variable for next loop


I am having a situation in which I need to clear the variable lastWord so that msgbox show nothing in next loop.

Following code is just an Example.

Sub clear_lastWord_Variable()

    Dim wordArr() As String
    Dim lastword As String
    Do
        selection.Find.ClearFormatting
        selection.Find.Font.Bold = True
        With selection.Find
            .Forward = True
            .Wrap = wdFindStop
        End With
        selection.Find.Execute

        If selection.Find.Found Then

            wordArr = Split(selection, " ")

            For i = LBound(wordArr) To UBound(wordArr) Step 1
                lastword = wordArr(i)

            Next i

            MsgBox lastword

            ' here should be something to clear lastword
        Else
            Exit Do
        End If
    Loop

End Sub

Solution

  • You can't "clear" a non-object variable, you can only set it to a defined value. For a string variable, that's usually the empty string "".

    lastword = ""
    

    or (identical)

    lastword = vbNullString
    

    For object variables, there is Set myObj = Nothing.