如何限制 Do While 循环中的循环次数?

How can I limit the number of loops in a Do While loop?

所以我编写了一个函数,它使用文本框输入在另一个 sheet 中搜索相应的值。问题是,如果找不到匹配项,它就会进入无限循环。我可以限制循环以免崩溃吗? 如果有另一种解决方案而不是限制循环,我会洗耳恭听。 这是我正在处理的内容:

Function Most_Recent_Deployment(Label1 As String, Label2 As String, Label3 As String) As Long
    Dim all_rows As Range
    Dim row As Range
    Dim LastCell As Range
    Dim LastCellRowNumber As Long
    Set LastCell = Sheet7.Cells(Sheet7.Rows.Count, "A").End(xlDown).End(xlUp)
    LastCellRowNumber = LastCell.row + 1
    Set row = Sheet7.Range("A:A").Find(Label1, LookIn:=xlValues, After:=Cells(LastCellRowNumber, "A"), SearchDirection:=xlPrevious)
    Do While row.row > 1

        If (Sheet7.Cells(row.row, 2).Text = Label2) And (Sheet7.Cells(row.row, 3).Text = Label3) Then
            Most_Recent_Deployment = row.row
            Exit Function
        End If
        LastCellRowNumber = row.row
        Set row = Sheet7.Range("A:A").Find(Label1, LookIn:=xlValues, After:=Cells(LastCellRowNumber, "A"), SearchDirection:=xlPrevious)

    Loop
    Most_Recent_Deployment = 0
End Function

您可以试试 Do Until。例如:

Do Until IsEmpty(Cells(iRow, 1)) 
    ' Store the current cell value in the dCellValues array
    dCellValues(iRow) = Cells(iRow, 1).Value
    iRow = iRow + 1 
Loop  

代码来自 ExcelFunctions.net.

您可以在 'Do While' 循环中添加一个 'AND' 片段,循环内有一个计数器,当您到达电子表格中的数据末尾时会显示该计数器。

类似于:

dim counter as integer    
Do While row.row > 1 and counter > worksheetfunction.counta(sheet7.range("A:A")

    If (Sheet7.Cells(row.row, 2).Text = Label2) And (Sheet7.Cells(row.row, 3).Text = Label3) Then
        Most_Recent_Deployment = row.row
        Exit Function
    End If
    LastCellRowNumber = row.row
    Set row = Sheet7.Range("A:A").Find(Label1, LookIn:=xlValues, After:=Cells(LastCellRowNumber, "A"), SearchDirection:=xlPrevious)
    coutner=counter+1

Loop

我的意思是,是的,它有点基础,但我认为它可以完成您正在寻找的工作,而无需过多更改您的代码。希望能帮助到你。

编辑:

LastCellRowNumber=row.row
temp2=temp1
temp1=LastCellRowNumber

Set row = Sheet7.Range("A:A").Find(Label1, LookIn:=xlValues, After:=Cells(LastCellRowNumber, "A"), SearchDirection:=xlPrevious)

if row.row=temp1 and temp1=temp2 then
    exit do
end if