Clear / Empty Variable for next loop

Ibn e Ashiq picture Ibn e Ashiq · May 15, 2016 · Viewed 98.5k times · Source

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

Answer

Andre picture Andre · May 15, 2016

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.