VBA-Excel find and select multiple cells

后端 未结 2 944
天涯浪人
天涯浪人 2020-12-11 10:00

i\'m writing a code and i\'m stuck on this problem which i think should not bee too difficult to solve but i don\'t manage it.

I need my program to find all cells w

相关标签:
2条回答
  • 2020-12-11 10:47

    As @Jeeped has already answered, using the Union Method will achieve what you were after.

    If the range you were searching for values within was to increase, it would be more efficient to use an Array to hold the values; you can then search the array instead of the worksheet.

    Just something to think about for the future.

    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
    
    0 讨论(0)
  • 2020-12-11 11:05

    Use the Union method to collect the ranges into one discontiguous range then .Select them before leaving the sub

    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
    
    0 讨论(0)
提交回复
热议问题