|
验证BOM是否无线嵌套。帮忙修改下代码,无法运行。
Option Explicit
' 用于记录已经访问过的行号,避免重复检查导致栈溢出等问题
Dim visitedRows As New Collection
Function CheckNested(ByVal currentValue As String, ByVal currentRow As Long) As Boolean
Dim parentValue As String
Dim foundRows As New Collection
Dim i As Long
Dim result As Boolean
' 将当前行号添加到已访问集合中
visitedRows.Add currentRow, CStr(currentRow)
' 获取当前C列值对应的B列父图号
parentValue = Application.VLookup(currentValue, Range("B:C"), 1, False)
If IsError(parentValue) Then
' 如果没找到父图号,说明不会继续嵌套了,返回False
CheckNested = False
Exit Function
End If
' 根据父图号在C列查找所有匹配的行号,并存入foundRows集合
FindAllMatchingRows parentValue, foundRows
' 如果没有找到匹配的行号,说明不会继续嵌套了,返回False
If foundRows.Count = 0 Then
CheckNested = False
Exit Function
End If
' 遍历找到的行号集合,进行递归检查
For i = 2 To foundRows.Count
Dim targetRow As Long
targetRow = foundRows(i)
' 如果当前行已经访问过,说明出现无限嵌套,返回True
If visitedRows.Contains(targetRow) Then
CheckNested = True
Exit Function
End If
' 递归调用,继续检查下一层
result = CheckNested(Application.VLookup(Application.Index(Range("C:C"), targetRow), Range("B:C"), 1, False), targetRow)
If result Then
CheckNested = True
Exit Function
End If
Next i
' 如果遍历完所有找到的行号都没有出现无限嵌套,返回False
CheckNested = False
End Function
Sub TestNested()
Dim lastRowC As Long
Dim i As Long
Dim isInfiniteLoop As Boolean
lastRowC = Cells(Rows.Count, "C").End(xlUp).Row
For i = 2 To lastRowC
visitedRows.Remove
isInfiniteLoop = CheckNested(Cells(i, "C").Value, i)
If isInfiniteLoop Then
MsgBox "在第 " & i & " 行开始出现无限嵌套情况。"
End If
Next i
MsgBox "整体检查完毕,未发现无限嵌套情况。"
End Sub
Sub FindAllMatchingRows(ByVal searchValue As String, ByRef resultRows As Collection)
Dim lastRowC As Long
Dim j As Long
lastRowC = Cells(Rows.Count, "C").End(xlUp).Row
For j = 2 To lastRowC
If Cells(j, "C").Value = searchValue Then
resultRows.Add j
End If
Next j
End Sub
|
|