Quantcast
Channel: dBforums – Everything on Databases, Design, Developers and Administrators
Viewing all articles
Browse latest Browse all 13329

Select and copy range of row if...

$
0
0
I'm creating a macro to select the range C through H in a row if the value in column C for that row is "IU". It looks like this works as long as the table is sorted by the C column. However, if there are any interruptions in column C, like if it goes IU, IU, IU, IN, IU. It will only select columns C through H for the first three rows and miss the last row. I'm thinking this must be an issue with my Do Until but looping in Excel VBA is still kind of mystifying to me. Any thoughts on what I'm doing wrong? Thanks Joshua

Code:

Sub Selectandcopy()

'THIS COPIES ALL RANGES FROM COLUMNS C THROUGH H
'WHERE THE STRING IN COLUMN C IS "IU"
   
    Const strTOFIND As String = "IU"

    Dim rngFound As Range, rngToCopy As Range
    Dim strFirstAddress As String
   
    With ActiveSheet.Range("C:C")
        Set rngFound = .Find( _
                            What:=strTOFIND, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=True)
        If Not rngFound Is Nothing Then
            Set rngToCopy = rngFound
            strFirstAddress = rngFound.Address
           
            Set rngFound = .FindNext(After:=rngFound)
           
            Do Until rngFound.Address = strFirstAddress
                Set rngToCopy = Application.Union(rngToCopy, rngFound)
                Set rngFound = .FindNext(After:=rngFound)
            Loop
        End If
    End With
    'COLUMNS BELOW ARE RELATIVE TO COLUMN C (i.e. A is C, F is H)
    If Not rngToCopy Is Nothing Then rngToCopy.Columns("A:F").Select

Selection.Copy

End Sub


Viewing all articles
Browse latest Browse all 13329

Trending Articles