VBA-Excel查找并选择多个单元格

时间:2015-07-26 09:39:49

标签: excel vba excel-vba

我正在写一个代码而且我坚持这个问题,我认为不应该太难解决,但我不管理它。

我需要我的程序找到具有特定值的所有单元格并选择它们。但是它们应该在子结束时保持选中状态。 所以我改变了一些我在网上找到的代码并写道:

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

当然它按顺序选择它们但它们不会保持选中状态,所以最后我只选择了最后找到的单元格

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

2 个答案:

答案 0 :(得分:3)

使用Union method将范围收集到一个不连续的范围内,然后在离开子

之前将其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 收集起来
e

答案 1 :(得分:1)

正如@Jeeped已经回答的那样,使用Union Method将实现您的目标。

如果您要搜索的值范围是增加的,那么使用Array来保存值会更有效率;然后,您可以搜索数组而不是工作表。

为未来考虑一下。

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