Excel:在Excel中获取周围的命名范围

时间:2013-07-04 07:54:21

标签: c# .net excel vsto ms-office

我有一个包含许多命名范围的Excel工作表,它具有层次结构(一个范围包含其他范围)。范围没有交叉点,也没有多重区域。如何估计特定命名范围的周围命名范围(换句话说,我希望得到类似父子关系的东西)。 例如: enter image description here

这里我有范围C.现在我想估计它的“父亲”。在这种情况下,它是B.

1 个答案:

答案 0 :(得分:2)

如果“父”总是完全包含子,并且是这样做的最小范围(就细胞计数而言),那么这可能会有所帮助。我确实认识到这是VBA,你的标签意味着VSTO,但这种方法可能仍然适用......

请注意,有很多案例没有检查过:命名公式就是这样。

Public Function ParentName(rng As Range) As String

Dim intersection As Range
Dim possibleParent As Range
Dim nm As Name

Dim rngCellCount As Long
Dim intersectCellCount As Long
Dim possParentCellCount As Long
Dim rangeParentCellCount As Long

    rngCellCount = rng.Cells.Count

    For Each nm In Names
        Set possibleParent = nm.RefersToRange
        Set intersection = Application.Intersect(rng, possibleParent) ' which cells are common between the target and possible parent?
        If Not intersection Is Nothing Then ' Nothing means no cells in common
            intersectCellCount = intersection.Cells.Count
            possParentCellCount = possibleParent.Cells.Count
            ' if intersection is same size as child then child is completely contained
            If intersectCellCount = rngCellCount And possParentCellCount > intersectCellCount Then
                If rangeParentCellCount > possParentCellCount Or rangeParentCellCount = 0 Then
                    ' record name of parent if smaller than best so far (or if we haven't already found a parent at all)
                    parentName = nm.Name
                    rangeParentCellCount = possParentCellCount
                End If
            End If
        End If
    Next

End Function