简体   繁体   English

如何退出“do while”语句

[英]How do I exit a “do while” statement

Sub FindValue()

Dim firstAddress As String
Dim Expense As String
Dim rRange As Range
Dim FirstrngFnd As Range
Dim x As Integer
Dim y As Integer
Dim z As Integer

Workbooks.Open FileName:= _
    "D:\My Documents\Excel Files\AA Credit Card\1008.xlsx"        'A worksheet with several columns - Column G (Column 7) is a list of "expenses".  
Workbooks.Open FileName:= _
    "D:\My Documents\Excel Files\Credit Card Analysis.xlsx"       'A worksheet with "expenses" listed in random order in Column A (Column1)
Windows("Credit Card Analysis.xlsx").Activate
ActiveWindow.Panes(1).Activate

Expense = Application.InputBox("Select the required expense from Column A")     'Pick an "expense" from a list in Column A

'Open the first file in the first folder
Windows("1008.xlsx").Activate
ActiveWindow.Panes(1).Activate

'Establish the first and last rows in Column A (which contain a list of dates by increasing date): required to establish the search range
Set rRange = Range("A1", Cells(Rows.Count, 1).End(xlUp))
    For Each rCell In rRange
        If IsDate(rCell) Then
            rCell(2, 1).Select
    Exit For
        End If
    Next rCell

x = (ActiveCell.Row - 1)                          'This finds the FIRST row in the file with a date in it
y = Cells(Rows.Count, 1).End(xlUp).Row            'This finds the LAST row in the file with a date in it
My_Workbook = ActiveWorkbook.Name                                               'Holds the current Workbook name

'Move over to the "analysis" column (G) (Column 7)
With Worksheets(1).Range(Cells(x, 7), Cells(y, 7))
    Set FirstrngFnd = .Find(Expense, LookIn:=xlValues, LookAt:=xlPart)          'Finds the first occurrence of "expense"
        If Not FirstrngFnd Is Nothing Then                                      'if the "expense" isn't listed then goto Line400
            firstAddress = FirstrngFnd.Address
        Do           'DO WHATEVER IS REQUIRED IN THIS SECTION: FROM "DO" TO "Set FirstrngFnd = .FindNext(FirstrngFnd)"
            z = FirstrngFnd.Row
            FirstrngFnd.Value = "Mike"        'IF YOU OMIT THIS LINE THEN ALL THE VALUES REMAIN AT "expense", SO THE PROGRAM JUST GOES ROUND (AND ROUND) AGAIN.
            Set FirstrngFnd = .FindNext(FirstrngFnd)
        Loop While Not FirstrngFnd Is Nothing
    End If
End With
End Sub

If I remove the line "FirstrngFnd.Value = "Mike" then the values in Golumn G never change so when the program gets to the end of the file, it just goes round again.如果我删除 "FirstrngFnd.Value = "Mike" 行,那么 Golumn G 中的值永远不会改变,所以当程序到达文件末尾时,它会再次循环。

How can I get it to recognise it's been through the file once, and to move on?我怎样才能让它识别出它已经通过文件一次,然后继续前进?

Please, modify:请修改:

Loop While Not FirstrngFnd Is Nothing

in this way:这样:

Loop While Not FirstrngFnd Is Nothing And FirstrngFnd.Address <> firstAddress 

Find in an Endless Loop在无限循环中查找

  • This covers the case when you are using the Find method (incl. FIndNext ) to find all occurrences of a value in a range, but you don't want to change them and you also don't want to end up in an endless loop.这涵盖了当您使用Find方法(包括FIndNext )查找范围内所有出现的值,但您不想更改它们并且您也不想最终陷入无限循环的情况.
  • To simplify, the procedures use Sheet1 (CodeName) and the range "A1:A3" and "Yes" as the criteria.为简化起见,程序使用Sheet1 (CodeName) 和范围“A1:A3”和“是”作为标准。
  • Copy them into a new workbook.将它们复制到新工作簿中。
  • Test first both procedures without values, then put in some "Yes" values (without the double quotes) in the cells.首先测试两个没有值的过程,然后在单元格中输入一些“是”值(没有双引号)。 You can also change the range to eg A1:A10 , to better understand.您还可以将范围更改为例如A1:A10 ,以便更好地理解。

The Code编码

Option Explicit

' To exit the endless loop, press and hold down the ESC key.
Sub testEndlessLoop()
    
    Dim rng As Range
    Dim cel As Range
    
    Set rng = Sheet1.Range("A1:A3")
    Set cel = rng.Find( _
        What:="Yes", _
        After:=rng(rng.Cells.Count), _
        LookIn:=xlFormulas)
    
    ' Assuring that a cel containing "Yes" has been found. Once it has
    ' been found, find will always find an occurrence of "Yes" whether
    ' there is one, two or three occurrences in the range,
    ' which will result in an endless loop (Do Loop).
    If Not cel Is Nothing Then
        ' A cell containing "Yes" has been found.
        
        Do
            MsgBox "Found ""Yes"" in cell '" & cel.Address & "'."
            ' Find the next occurrence of "Yes"
            Set cel = rng.FindNext(cel)

        ' 'While Not cel Is Nothing' is redundant because 'cel' will
        ' never be 'Nothing' anyway, which is ensured previously with
        ' 'If Not cel Is Nothing Then'.
        Loop While Not cel Is Nothing
    
    Else
        ' A cell containing "Yes" has not been found.
        MsgBox "No occurrences found."
    End If

End Sub

Sub testWorkingLoop()
    
    Dim rng As Range
    Dim cel As Range
    Dim FirstAddress As String
    
    Set rng = Sheet1.Range("A1:A3")
    Set cel = rng.Find( _
        What:="Yes", _
        After:=rng(rng.Cells.Count), _
        LookIn:=xlFormulas)
    
    If Not cel Is Nothing Then
        ' A cell containing "Yes" has been found.

        ' Write the range address of the first found occurrence to a variable.
        FirstAddress = cel.Address
        
        Do
            ' This is where you do stuff when "Yes" is found.
            
            MsgBox "Found ""Yes"" in cell '" & cel.Address & "'."
            ' Most often you don't want to change the found cell,
            ' but you want to change another cell in the same row,
            ' e.g. write to the cell in column 'B'.
            cel.Offset(0, 1).Value = "Found a ""Yes""."
            
            ' This is where you do stuff when "Yes" is found.
            
            ' Find the next occurrence of "Yes"
            Set cel = rng.FindNext(cel)
        
        ' Again, 'cel' will never be 'Nothing'.
        Loop While cel.Address <> FirstAddress
    
    Else
        ' A cell containing "Yes" has not been found.
        MsgBox "No occurrences found."
    End If

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM