2

Having a problem with If, ElseIf, Else function in VBA.

My code needs to look for "Text1", elseIf needs to look for "Text2", else make a note in a log file.

The problem is I can't seem to change the Find parameters as part of the ElseIF..

ElseIf Selection.Find.ClearFormatting    
With Selection.Find
  .Forward = False
  .Text = "Text2"
End With                                            
Selection.Find.Execute Then

The ElseIF will only work if I put it infront of The execute line, this means im still searching "Text1" that doesn't exist.

ElseIf Selection.Find.Execute Then

Any idea where im going wrong?

Full code:

Sub Testing()

    Dim LogFile As String

    LogFile = "G:\ErrorLog.txt"

    Selection.Find.ClearFormatting
    With Selection.Find
        .Forward = False
        .Text = "Text1"
    End With

    If Selection.Find.Execute Then

        MsgBox "Found Text1"

        Selection.Find.ClearFormatting
        With Selection.Find
            .Forward = False
            .Text = "Text2"
        End With

    ElseIf Selection.Find.Execute Then

         MsgBox "Found Text2"

    Else

        Open LogFile For Append As #1
        Print #1, Now & " " & "Text Field Error" & ": "
        Close #1

    End If

End Sub

1 Answer 1

4
**If Selection.Find.Execute Then**
       MsgBox "Found Text1"

       Selection.Find.ClearFormatting
       With Selection.Find
           .Forward = False
           .Text = "Text2"
       End With

 **ElseIf Selection.Find.Execute Then**

Look the **... These are looking for same. How can it popup an value by same? At least it only can found text 1 or else, but not ElseIf. So you should delete ElseIf become If only.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.