我不是程序员,所以请原谅我 这是一个简单的问题。我就是不 知道如何克服它。我有输入 在另一个框中搜索文本字符串的框 Excel工作表。输入框有效,并且 消息框也可以,但是我无法停止 搜索。不断寻找下一个 通过一切。我想按 否按钮并打破循环退出, 但是无论我按什么按钮 将继续到下一个。有人可以吗 帮我吗?
Sub FindWONumber ()
Application.ScreenUpdating = False
Sheets("All Projects").Select
Range("A4").Select
Dim SearchRange As Range
Dim ProjectName As Range
Dim WorkOrderNumber As String
Dim FirstProjectName As String
WorkOrderNumber = InputBox("Type in Work Order Number")
Set SearchRange = Range("B3", Range("B4").End(xlDown))
Set ProjectName = SearchRange.FIND(What:=WorkOrderNumber, MatchCase:=False, LookAt:=xlPart)
If ProjectName Is Nothing Then
Sheets("Display Buttons").Select
ActiveWindow.Zoom = 85
Range("W12").Select
MsgBox "No Work Order Number was found"
Else
Application.ScreenUpdating = True
ProjectName.Select
FirstProjectName = ProjectName.Address
Do
Set ProjectName = SearchRange.FindNext(ProjectName)
ProjectName.Select
Dim ButtonClicked As VbMsgBoxResult
ButtonClicked = MsgBox("Find Next", vbQuestion + vbYesNo, Title:="Search String")
Loop While ProjectName.Address <> FirstProjectName
If ButtonClicked = vbYes Then
MsgBox "Search Complete"
ElseIf ButtonClicked = vbNo Then
MsgBox "Stop"
Else
End If
End If
End Sub
答案 0 :(得分:0)
我重新缩进了您的代码(如下所示),并添加了一些解释性注释。希望现在,可以更轻松地看到代码中的逻辑流。
仅在第一个Else
代码块的If-Else
语句内,将屏幕更新更改为true,然后为FirstProjectName
设置变量。之后,您将在Do-Loop
中找到下一个,然后要求继续(从msgbox存储结果)。然后代码比较项目名称并在满足条件的情况下循环。循环完全结束后,您就有逻辑(另一个If-Else
语句)查看msgbox中的结果,并根据该结果进行条件编码。
由于您希望msgbox中的结果影响Do-Loop
(仅当结果为vbYes
时才继续循环),因此应更改:
Loop While ProjectName.Address <> FirstProjectName
收件人:
Loop While ProjectName.Address <> FirstProjectName And ButtonClicked = vbYes
(我还将将msgbox结果变量Dim ButtonClicked As VbMsgBoxResult
的声明与其他变量声明一起移向代码的开头。)
原始代码
Sub FindWONumber ()
Application.ScreenUpdating = False
Sheets("All Projects").Select
Range("A4").Select
Dim SearchRange As Range
Dim ProjectName As Range
Dim WorkOrderNumber As String
Dim FirstProjectName As String
WorkOrderNumber = InputBox("Type in Work Order Number")
Set SearchRange = Range("B3", Range("B4").End(xlDown))
Set ProjectName = SearchRange.FIND(What:=WorkOrderNumber, MatchCase:=False, LookAt:=xlPart)
If ProjectName Is Nothing Then
Sheets("Display Buttons").Select
ActiveWindow.Zoom = 85
Range("W12").Select
MsgBox "No Work Order Number was found"
Else
Application.ScreenUpdating = True
ProjectName.Select
FirstProjectName = ProjectName.Address
' Start of loop
Do
Set ProjectName = SearchRange.FindNext(ProjectName)
ProjectName.Select
Dim ButtonClicked As VbMsgBoxResult
ButtonClicked = MsgBox("Find Next", vbQuestion + vbYesNo, Title:="Search String")
' End of loop
Loop While ProjectName.Address <> FirstProjectName
' Done after loop above has finished
If ButtonClicked = vbYes Then
MsgBox "Search Complete"
ElseIf ButtonClicked = vbNo Then
MsgBox "Stop"
Else
End If
End If
End Sub