要实现这个功能,可以使用递归的方式来遍历父子节点。以下是一个示例的VBA代码:

Sub FindNodes()
    Dim inputChar As String
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim currentNode As Range
    
    ' 获取输入字符
    inputChar = Worksheets("Sheet1").Range("C1").Value
    
    ' 设置工作表
    Set ws1 = Worksheets("Sheet1")
    Set ws2 = Worksheets("Sheet2")
    
    ' 清空Sheet2中的数据
    ws2.Cells.Clear
    
    ' 在Sheet1的A列中查找输入字符
    Set currentNode = ws1.Range("A1").End(xlDown)
    Do Until currentNode.Value = inputChar
        Set currentNode = currentNode.Offset(-1, 0)
    Loop
    
    ' 调用递归函数,将找到的节点输出到Sheet2中
    FindAndOutputNodes currentNode, ws2
    
    MsgBox "查找完成!"
End Sub

Sub FindAndOutputNodes(node As Range, outputSheet As Worksheet)
    Dim parentNode As Range, childNode As Range
    Dim nextNode As Range
    
    ' 输出当前节点
    outputSheet.Cells(outputSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1).Value = node.Value
    
    ' 查找父节点
    If Not node.Offset(0, -1).Value = "" Then
        Set parentNode = node.Offset(0, -1)
        FindAndOutputNodes parentNode, outputSheet
    End If
    
    ' 查找子节点
    If Not node.Offset(0, 1).Value = "" Then
        Set childNode = node.Offset(0, 1)
        Do Until childNode.Value = ""
            outputSheet.Cells(outputSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1, 1).Value = childNode.Value
            Set nextNode = childNode.Offset(0, 1)
            FindAndOutputNodes nextNode, outputSheet
            Set childNode = nextNode
        Loop
    End If
End Sub

在上述代码中,首先获取输入字符,并设置两个工作表对象。然后清空Sheet2中的数据。接下来,在Sheet1的A列中查找输入字符,并将找到的节点传递给递归函数FindAndOutputNodes。递归函数根据当前节点找到其父节点和子节点,并将它们输出到Sheet2中。最后,弹出一个消息框提示查找完成


原文地址: https://www.cveoy.top/t/topic/iqYm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录