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

所以我写了一个函数,它使用文本框input在另一个工作表中search相应的值。 问题是,如果它没有find一个匹配进入一个无限循环。 我可以限制循环,使其不会崩溃吗? 如果还有其他的解决scheme,而不是限制循环,那么我就是耳朵。 以下是我正在处理的内容:

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 

您可以在循环中添加一个“AND”部分到“Do While”循环中,该循环中将有一个计数器指示您何时到达电子表格中的数据末尾。

就像是:

 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 

你可以尝试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的代码。