我想从列中的选择列表(CTRL+ Click)中排除最顶层的选择。例如,如果我选择了V12 + V10 + V14 + V9。最上面的选项是V9。我有这个循环遍历所有选定单元格的代码,但我需要排除最上面的选定内容(即V9)。
下面是工作代码:
Dim rngPart as Range
For Each rngPart in Application.Selection.Areas
MsgBox rngPart.Address
Next我需要帮助来排除最上面的选项
发布于 2019-06-28 05:47:25
我会把它分解成几个函数,把它们组合在一起。
首先,我想要一个函数根据它所在的行来查找最上面的区域。要做到这一点,我们只需要一个简单的循环,如果范围小于前一个单元格,则指定范围。
Private Function getTopRange(ByRef source As Range) As Range
Dim cell As Range
For Each cell In source
If getTopRange Is Nothing Then
Set getTopRange = cell
End If
If cell.Row < getTopRange.Row Then
Set getTopRange = cell
End If
Next cell
End Function然后,我将创建一个函数,该函数将返回不包括顶部的范围。
要做到这一点,我们只需要一个简单的循环。如果它不是顶部的单元格,则将其合并到我们的返回范围值。
Private Function excludeTopRange(ByRef source As Range) As Range
Dim topRange As Range
Set topRange = getTopRange(source)
Dim cell As Range
For Each cell In source
' Only add if not the top cell
If cell.Address <> topRange.Address Then
If excludeTopRange Is Nothing Then
Set excludeTopRange = cell
Else
Set excludeTopRange = Union(excludeTopRange, cell)
End If
End If
Next cell
End Function把所有这些放在一起,你只需要调用我们的新函数!
Private Sub test()
Dim source As Range
Set source = Application.Selection
Dim excluded As Range
Set excluded = excludeTopRange(source)
MsgBox excluded.Address
End Sub这是一个很好的design,试着让你的函数像这样保持小和可重用。它更易于阅读、调试、测试和重用!
https://stackoverflow.com/questions/56798381
复制相似问题