Excel vba 查找嵌套在另一个查找函数中

问题描述 投票:0回答:1

我想使用excel vba中的查找函数,然后,当找到一个值并且满足某些属性时,使用另一个查找函数来查找另一个值。不知何故,第一个 find 变量的搜索参数被第二个变量重置,并且在 .FindNext 语句之后,循环将永远运行。谁能看出错误吗?

Sub findInfind()
    Dim cell As Range
    Dim cellNew As Range
    Dim datatoFind
    Dim datatoFindNew
    Dim firstAddress As String
    
    datatoFind = 1
    datatoFindNew = 5

    With S_Staebe.Range("Knot_Nr_Ende")
        Set cell = .Find(What:=datatoFind, LookIn:=xlValues, LookAt:=xlWhole)

        If Not cell Is Nothing Then
            firstAddress = cell.Address
            Do
                'some code...
                ' if ... then ...
                    Set cellNew = .Find(What:=datatoFindNew, LookIn:=xlValues, LookAt:=xlWhole)
                ' endif
                'some code...
                
                Set cell = .FindNext(cell)
                If cell Is Nothing Then Exit Do
            Loop Until cell.Address = firstAddress
        End If
    End With
End Sub

我真的找不到与此相关的问题。

**编辑 这是我想要实现的一个示例: 在此输入图片描述

excel vba find
1个回答
0
投票

问题出在您编码的算法中。经过一些修改后它开始工作:

enter image description here

Option Explicit

Sub findInfind()
  Dim cell As Range, cellNew As Range
  Dim datatoFind, datatoFindNew
  Dim firstAddress$
  datatoFind = 10: datatoFindNew = 8
  With Sheet1.Range("Knot_Nr_Ende")
    Set cell = .Find(What:=datatoFind, LookIn:=xlValues, LookAt:=xlWhole)
    If Not cell Is Nothing Then
      Debug.Print "Outer", cell.Address
      Set cellNew = .Find(What:=datatoFindNew, After:=cell, LookIn:=xlValues, LookAt:=xlWhole)
      If Not cellNew Is Nothing Then
        Debug.Print "Inner", cellNew.Address
        firstAddress = cellNew.Address
        Do

            ' payload code here

            Set cellNew = .FindNext(cellNew)
            If cellNew Is Nothing Then Exit Do
            Debug.Print "Inner", cellNew.Address
            DoEvents
        Loop Until cellNew.Address = firstAddress
      End If
    End If
  End With
End Sub

理解问题所在并不那么复杂。

© www.soinside.com 2019 - 2024. All rights reserved.