C# Excel:在Excel中获取周围的命名范围
我有一个Excel表格,其中有许多命名的区域,它们具有层次结构(一个区域包含其他区域)。这些范围没有交点,也没有多峰区域。如何估计特定命名范围的周围命名范围(换句话说,我希望得到类似父子关系的东西)。 例如: 这里我有范围C。现在我想估计它的“父亲”。在这种情况下,是B.如果“父项”始终完全包含子项,并且是这样做的最小范围(在单元格计数方面),那么这可能会有所帮助。我知道这是VBA,你的标签暗示着VSTO,但这种方法可能仍然适用 请注意,有许多情况没有检查:命名公式就是这样一种情况C# Excel:在Excel中获取周围的命名范围,c#,.net,excel,vsto,ms-office,C#,.net,Excel,Vsto,Ms Office,我有一个Excel表格,其中有许多命名的区域,它们具有层次结构(一个区域包含其他区域)。这些范围没有交点,也没有多峰区域。如何估计特定命名范围的周围命名范围(换句话说,我希望得到类似父子关系的东西)。 例如: 这里我有范围C。现在我想估计它的“父亲”。在这种情况下,是B.如果“父项”始终完全包含子项,并且是这样做的最小范围(在单元格计数方面),那么这可能会有所帮助。我知道这是VBA,你的标签暗示着VSTO,但这种方法可能仍然适用 请注意,有许多情况没有检查:命名公式就是这样一种情况 Publi
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
举个例子可能会有所帮助。。