在VBA中遇到If,ElseIf,Else函数的问题。
我的代码需要查找“Text1”,否则需要查找“Text2”,否则在日志文件中记下。
问题是我似乎无法将Find参数更改为ElseIF的一部分..
ElseIf Selection.Find.ClearFormatting
With Selection.Find
.Forward = False
.Text = "Text2"
End With
Selection.Find.Execute Then
如果我把它放在执行线的前面,ElseIF只会工作,这意味着我仍在搜索不存在的“Text1”。
ElseIf Selection.Find.Execute Then
知道我哪里出错了?
完整代码:
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
答案 0 :(得分: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**
看看** ......这些都在寻找相同的东西。它怎么能弹出一个值呢?至少它只能找到文本1或其他,但不能找到ElseIf
。
因此,您应该仅删除ElseIf
成为If
。