我在隐藏列中有一个计算的值范围,我将其用于下拉框。为了确定用户选择了哪个值,我尝试在该范围上运行查找,但由于某些原因,只要该列被隐藏,Excel就不会返回与其选择对应的单元格。
如何在隐藏范围内的单元格上查找。请记住 - 我正在搜索单元格计算值,而不是公式。
以下不起作用:
Set inserted = Range("RDS_Event_IDs").Find(Range("SelectedEvent"), , xlValues, xlWhole)
只要Range("RDS_Event_IDs")
中的单元格被隐藏。
由于解决方案必须在一般情况下工作,其中可能隐藏搜索范围中的部分或全部,并且可能搜索整个工作表,因此以编程方式取消隐藏所有受影响的行和列是不可行的然后重新隐藏之前隐藏的那些。
答案 0 :(得分:22)
根据Andy Pope(并且他从来没有错)如果您正在使用xlFormulas,则只查找隐藏单元格的作品。也许是匹配?
Set inserted = Cells(Application.WorksheetFunction.Match("SelectedEvent", Range("RDS_Event_IDs"), 0), Range("RDS_Event_IDs").Column)
答案 1 :(得分:2)
真的需要在宏内部进行,使用匹配会更容易:
=MATCH(G9;H9:H16;0)
G9:DropDownBox的单元格
H9:H16:你的范围
0:完全匹配
它返回数组中的索引
答案 2 :(得分:0)
使用 Doug Glancy 的答案,最好将其放入函数中以实现可重用性。
''
' Find a range using `WorksheetFunction.Match()`. This alternative works well
' for finding range in hidden cells, and is not case sensitive.
'
' Created this solution based on answer on Stack Overflow @see https://stackoverflow.com/a/6298404/8309643
'
' @author Robert Todar <robert@roberttodar.com>
''
Function Find(ByRef searchRange As Range, ByVal what As String) As Range
Set Find = Cells(Application.WorksheetFunction.Match(what, searchRange, 0), searchRange.Column)
End Function
搜索范围的另一种方法是从范围中获取数组并循环。同样,把它放在一个函数中可以很容易地重用!
''
' Finds a range based on it's value.
' This works faster than `Range.Find()` as it loops an array instead of cells.
' This also works for hidden cells where `Range.Find` does not.
'
' Note, this looks for first match, and is case sensitive by defaut, unless
' Option Match Case is used at the top of the module it is stored in.
'
' @author Robert Todar <robert@roberttodar.com>
''
Public Function FindFast(searchRange As Range, what As String) As Range
' Get data from range into an Array. Looping Arrays is much
' faster than looping cells.
Dim data As Variant
data = searchRange.Value
' Loop every row in the array.
Dim rowIndex As Long
For rowIndex = LBound(data, 1) To UBound(data, 1)
' Loop every column in the array.
Dim columnIndex As Long
For columnIndex = LBound(data, 2) To UBound(data, 2)
' If current row/column matches the correct value then return the range.
If data(rowIndex, columnIndex) Like what Then
Set FindFast = searchRange.Cells(rowIndex, columnIndex)
Exit Function
End If
Next columnIndex
Next rowIndex
' If the range is not found then `Nothing` is returned.
Set FindFast = Nothing
End Function