8

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

2 Answers 2

23

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.

2
  • 1
    Please look below, VARIANT type variable can be set to EMPTY and then checked by IsEmpty() function. May 2, 2020 at 20:33
  • That is correct for Variant. The question was about String variables though. @MilanOparnica
    – Andre
    May 3, 2020 at 7:34
8

If your variable is not an object you can also do:

lastword = Empty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.