所以我编写了一个函数,它使用文本框输入来搜索另一个工作表中的相应值。问题是如果找不到匹配则进入无限循环。我可以限制循环,以免崩溃吗? 如果有另一种解决方案而不是限制循环,我会全力以赴。 以下是我正在使用的内容:
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
答案 0 :(得分:0)
您可以尝试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的代码。
答案 1 :(得分:0)
您可以在“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