【发布时间】:2021-11-27 09:43:10
【问题描述】:
我有一个查找功能,可以搜索一列,并且可能有多个结果。我想将其存储在一个范围内(例如,而不是单独的数组)。 这就是我所拥有的:
Dim searchRange As Range
Set searchRange = ActiveWorkbook.Sheets(SHEET).Range(SEARCHFOLDERCOLUMN & SEARCHSTARTROW & ":" & SEARCHFOLDERCOLUMN & lastRow)
'search for value
Dim searchResult As Range
Dim firstAddress As String
Set searchResult = searchRange.Find(what:=sSearchFolder, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not searchResult Is Nothing The
firstAddress = searchResult.Address
Do
'search for the next one
Debug.Print searchResult.Address
Set searchResult = searchRange.FindNext(searchResult)
'^^^^^ union instead of this ???
'avoid endless loop, when hitting back the first address
If firstAddress = searchResult.Address Then
'Set searchResult = tempSearchResult
Exit Do
End If
Loop While Not searchResult Is Nothing
End If
Debug.Print "out of loop"
我的输出:
$M$125
$M$148
$M$161
out of loop
我怎样才能得到这样的范围: "$M$125, $M$148, $M$161" ?列(或行?)或 3 而不是我现在的 1。
感谢您的帮助。
【问题讨论】:
-
您使用
Union(例如rgAllFound = Union(rgAllFound, rgThisFind)。但请注意,因为您不能Union第一种情况。您需要设置第一种情况(例如If rgAllFound is Nothing then Set rgAllFound = rgThisFind Else rgAllFound = Union(rgAllFound, rgThisFind)。跨度> -
我在previous answer 中编写了一个函数来执行此操作。如果您需要将搜索限制为一列而不是整个工作表,您只需将
WithinSheet编辑为Range而不是Worksheet。 -
@Toddleson 你好,感谢你之前的回答,我可以使用你的代码从那个答案中让我的(几乎)工作,但范围的大小似乎仍然是一个。我有这个:设置 searchResult = FindAll(sSearchFolder, SearchRange) Debug.Print searchResult.Address Debug.Print searchResult.Columns.Count & " / " & searchResult.Rows.Count。输出为:$M$125,$M$148,$M$161。(输入)。 1 / 1。为什么行或列仍然是 1 ?
-
@Toddleson 好的,我必须使用“计数”而不是行和列大小,谢谢!