首页 > 解决方案 > 查找跳过行或查找同一行

问题描述

这是我的 Excel 文件的一部分(wsPct在代码中)

行号 ID 公司 百分
573 1433 AAA 1
574 1433 BBB 0
575 1433 CCC 0
576 1435 DDD 1

和我的 VBA 代码的一部分

If IsNumeric(wsMerge.Cells(rowNum, "O").Value) Then
   ' Find ID in wsPct
   Set whereFound = wsPct.Columns("A").Find(wsMerge.Cells(rowNum, "O").Value, LookIn:=xlValues, lookat:=xlWhole)
    
   Do While Not whereFound Is Nothing
      ' Check for company match
      If wsPct.Cells(whereFound.Row, "B").Value = wsMerge.Cells(rowNum, "B").Value Then
         wsMerge.Cells(rowNum, "E").Value = wsPct.Cells(whereFound.Row, "C").Value
      End If
                
      ' Search for next match
      Set whereFound = Range(wsPct.Cells(whereFound.Row + 1, "A"), wsPct.Cells(numRows, "A")).Find(wsMerge.Cells(rowNum, "O").Value, LookIn:=xlValues, lookat:=xlWhole)
   Loop
End If

当我运行此程序以查找 ID=1433 和 Company=BBB 时,它最初将Find位于第 573 行。当它搜索下一个匹配项时,它将位于Find第 575 行。因此,它永远找不到正确的行 (574)。如果我将第二个更改Find为(丢失+1

      Set whereFound = Range(wsPct.Cells(whereFound.Row, "A"), wsPct.Cells(numRows, "A")).Find(wsMerge.Cells(rowNum, "O").Value, LookIn:=xlValues, lookat:=xlWhole)

然后它将继续到Find第 573 行(无限循环)。

我怎样才能把它放到Find第 574 行?

标签: excelvba

解决方案


Find()有一堆参数决定了它是如何工作的,所以如果你想使用这种方法(而不是更典型的FindNext),你必须考虑一下,但它可以工作。

这是一个例子:

Sub Tester()

    Dim ws As Worksheet, rngFind As Range, f As Range, v
    
    Set ws = ActiveSheet
    Set rngFind = ws.Columns("a")
    
    v = 1433

    'Find always wraps back to the start of the range, so start after
    '  the last cell to ensure it starts looking in the first cell...
    Set f = rngFind.Find(v, after:=rngFind.Cells(rngFind.Cells.Count), _
                         lookat:=xlWhole, searchdirection:=xlNext)
    
    Do While Not f Is Nothing
        Debug.Print f.Row
        
        Set rngFind = ws.Range(f.Offset(1, 0), ws.Cells(Rows.Count, "A"))
        Set f = rngFind.Find(v, after:=rngFind.Cells(rngFind.Cells.Count), _
                             lookat:=xlWhole, searchdirection:=xlNext)
    
    Loop

End Sub

推荐阅读