VBA-Excelfind并select多个单元格

我正在写一个代码,我卡在这个问题,我认为不应该蜜蜂太难解决,但我不pipe理它。

我需要我的程序来查找具有特定值的所有单元格并select它们。 但是他们应该在小组结束时保持被选中。 所以我改变了一下我在网上find的代码,并写道:

Sub FindAll() With Worksheets(4).Range("a1:l500") Set c = .Find("myValue", LookIn:=xlValues) If Not c Is Nothing Then firstAddress = c.Address Do Worksheets(4).Range(c.Address).Activate Set c = .FindNext(c) Loop While Not c Is Nothing And c.Address <> firstAddress End If End With End Sub 

当然,它会依次select它们,但是它们不会保持选中状态,所以最后我只是select了最后一个find的单元格

任何人都可以帮我解决吗? 提前致谢

使用联合方法将范围收集到一个不连续的范围,然后在离开子之前select它们

 Sub FindAll() Dim firstAddress As String, c As Range, rALL As Range With Worksheets(4).Range("a1:l500") Set c = .Find("myValue", LookIn:=xlValues) If Not c Is Nothing Then Set rALL = c firstAddress = c.Address Do Set rALL = Union(rALL, c) Worksheets(4).Range(c.Address).Activate Set c = .FindNext(c) Loop While Not c Is Nothing And c.Address <> firstAddress End If .Activate If Not rALL Is Nothing Then rALL.Select End With End Sub 

正如@Jeeped已经回答,使用联盟方法将达到你以后的。

如果search范围内的值增加,使用数组来保存值会更有效; 您可以search数组而不是工作表。

只是要考虑未来。

 Option Explicit Sub arrayFindAll() Dim wb As Workbook, ws As Worksheet Dim myArr() As Variant, myCells() As Integer Dim i As Long, j As Integer, k As Integer, m As Integer Dim valOccurence As Integer Dim unionCells As Range, lookupRng As Range Set wb = ThisWorkbook Set ws = wb.Sheets(4) Set lookupRng = ws.Range("A1:L500") myArr = lookupRng valOccurence = WorksheetFunction.CountIf(lookupRng, "myValue") - 1 ReDim myCells(0 To valOccurence, 0 To 1) For i = LBound(myArr, 1) To UBound(myArr, 1) For j = LBound(myArr, 2) To UBound(myArr, 2) If myArr(i, j) = "myValue" Then For k = 0 To UBound(myCells, 1) If myCells(k, 0) = 0 Then myCells(k, 0) = i myCells(k, 1) = j Exit For End If Next k End If Next j Next i Set unionCells = Cells(myCells(m, 0), myCells(m, 1)) For m = 1 To valOccurence Set unionCells = Union(unionCells, Cells(myCells(m, 0), myCells(m, 1))) Next m unionCells.Select End Sub