使用两个FindNext时出错

时间:2016-08-24 15:07:39

标签: vba

此代码有两个range.find / findnext,用于在父/子值列表中搜索值和相关值。

为父值创建字典的唯一值,然后使用字典作为父级在两个循环中使用范围查找。

Sub tablaplana()
  Call SET_VAR
  '# FIND UNIQUE REGION CENTERS
  ' Dim region As Range
  ' Dim district As Range
  Set dict = CreateObject("Scripting.Dictionary")
  With ws(3)
      r = 2
    x = 2
    Do Until x >= .Range("A1").End(xlDown).Row
        jnum = .Cells(x, 3)
        jtype = .Cells(x, 4)
        jname = .Cells(x, 6)
        If jtype = "R" And InStr(1, jname, "REGION ADMIN") Then
            If Not dict.Exists(jnum) Then
                dict.Add jnum, jname
                Debug.Print x
            End If
        End If
        x = x + 1
    Loop
    '# FIND ALL SUB-SUB-VALUES VALUES OF PARENT UNIQUE VALUES
    For Each k In dict.Keys
        s = 0
        Set region = .Range("C:C").Find(k, LookAt:=xlWhole)
        If Not region Is Nothing Then
            regionfirst = region.Address
            Do
                Set district = .Range("C:C").Find(.Cells(region.Row, 1), LookAt:=xlWhole)
                If Not district Is Nothing Then
                    districtfirst = district.Address
                    Do
                        '# ADD VALUES TO REPORT SHEET
                        ws(1).Cells(r, 1) = .Cells(district.Row, 1) 'sub-sub number
                        ws(1).Cells(r, 2) = .Cells(region.Row, 6) 'parent name
                        ws(1).Cells(r, 3) = .Cells(region.Row, 3) 'parent number
                        ws(1).Cells(r, 4) = .Cells(district.Row, 6) 'sub name
                        ws(1).Cells(r, 5) = .Cells(district.Row, 3) 'sub number
                        ws(1).Cells(r, 6) = .Cells(district.Row, 5) 'sub-sub name
                        Set district = .Range("C:C").FindNext(district)
                        r = r + 1
                    Loop While Not district Is Nothing And district.Address <> districtfirst
                End If
                Set region = .Range("C:C").FindNext(region)
            Loop While Not region Is Nothing And region.Address <> regionfirst
        End If
      Next k
  End With
End Sub

使用两个Range.Find和FindNext会导致错误。在到达第二个FindNext(区域)时,返回的值等于第一个FindNext(区域),即使它正在寻找Region。

同样暗淡,因为区域会在同一时间创建错误消息。

0 个答案:

没有答案