Excel:在Excel中获取周围的命名区域

我有一个Excel工作表与许多命名范围,其中有一个分层结构(一个范围包含其他范围)。 范围没有交点,也没有多翼区域。 我怎样才能估计一个特定命名范围的范围(换句话说,我想要得到一个像父子关系的东西)。 对于例子: 在这里输入图像说明

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

如果“父母”总是完全包含孩子,并且是这样做的最小范围(就细胞数而言),那么这可能有帮助。 我意识到这是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