1

所以我编写了一个函数,它使用文本框输入在另一张表中搜索相应的值。问题是如果找不到匹配项,它会进入无限循环。我可以限制循环使其不会崩溃吗?如果有另一种解决方案而不是限制循环,我会全力以赴。这是我正在使用的:

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
4

2 回答 2

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
于 2015-04-01T16:32:35.373 回答
0

你可以试试做直到。例如:

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的代码。

于 2015-04-01T16:14:45.520 回答