列A包含列中唯一的相同值列表。此列表的长度未知。确定列表上限和下限的最有效方法是什么?
A | B | C | ...
--------------------------
... |
AAA |
AAA |
AAA |
AAA |
AAA |
AAA |
... |
当然,这可以通过从开始位置向下和向上迭代直到您达到不同的值来解决。但是对于更大的列表我怀疑这是一个很好的解决方案。在这种情况下是否有任何内置的Excel功能可以为我提供性能优势?
答案 0 :(得分:0)
以下是一些您可以调整的示例代码:
Sub TheOuterLimits()
Dim r As Long, v As Variant
Dim a1 As String, a2 As String
Dim i As Long, c As Long
r = ActiveCell.Row
c = ActiveCell.Column
v = ActiveCell.Value
a1 = ""
a2 = ""
For i = r To 1 Step -1
If Cells(i, c).Value <> v Then
a1 = Cells(i, c).Address(0, 0)
Exit For
End If
Next i
For i = r To Rows.Count
If Cells(i, c).Value <> v Then
a2 = Cells(i, c).Address(0, 0)
Exit For
End If
Next i
MsgBox a1 & vbCrLf & a2
End Sub
代码告诉您模式的开始位置和结束位置。
答案 1 :(得分:0)
除了Scott Craner在评论中指出的内置Excel功能外,您可以考虑这个小VBA功能
Function GetArea(rng As Range) As String
With rng.EntireColumn
.AutoFilter field:=1, Criteria1:=rng.Value 'ActiveCell.Value
GetArea= .Resize(.Rows.count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Areas(1).address
.Parent.AutoFilterMode = False
End With
End Function
在你的&#34; Main&#34;中被利用代码如下:
Sub Main()
MsgBox getarea(Range("A12")) '<--| get the bound of the list one element of which is cell A12
End Sub