VBA IF ElseIF 其他

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16310541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:31:38  来源:igfitidea点击:

VBA IF ElseIF Else

vbaif-statementms-wordword-vba

提问by Michael Carn-Bennett

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

VBA 中的 If、ElseIf、Else 函数有问题。

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

我的代码需要查找“Text1”,elseIf 需要查找“Text2”,否则在日志文件中记下。

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

问题是我似乎无法将 Find 参数更改为 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 仅在我将它放在执行行前面时才起作用,这意味着我仍在搜索不存在的“Text1”。

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

回答by Kasnady

**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 ElseIfbecome Ifonly.

看**...这些都在寻找相同的。它如何通过相同的方式弹出一个值?至少它只能找到文本 1 或 else,但不能找到ElseIf。所以你应该删除ElseIf成为Ifonly。