Search code examples
excelvbareferencecell

How to reference cells in range?


Based on the text ("SNV") present in column L of the "HiddenSheet" worksheet, I would like to select and copy cells in columns 1 to 6 for all rows for which the "SNV" text is present in column L.

Then I would like to paste the values of the copied cells in the SNVReports worksheet.

Sub Macro2()

a = Worksheets("HiddenSheet").Cells(Rows.Count, 1).End(xlUp).Row

For i = 1 To a

    If Worksheets("HiddenSheet").Cells(i, 12).Value = "SNV" Then

        Worksheets("HiddenSheet").Range(Cells(i, 1), Cells(i, 6)).Copy
        Worksheets("SNVReports").Activate
        b = Worksheets("SNVReports").Cells(Rows.Count, 1).End(xlUp).Row
        Worksheets("SNVReports").Cells(b + 1, 1).Select
        ActiveSheet.Paste
        Worksheets("HiddenSheet").Activate

    End If
Next

Application.CutCopyMode = False

End Sub

I sometimes receive:

"Application-defined or object-defined error"

and it is apparently related to my range:

Worksheets("HiddenSheet").Range(Cells(i, 1), Cells(i, 6)).Copy

Solution

  • Your Cells(i,#) references aren't qualified. So if the SNVReports tab is active when the macro runs, it's confused as to what range you're talking about.

    The whole code could do with a tidy-up:

    Sub Macro2a()
    
        Dim sourcesheet As Worksheet
        Dim destsheet As Worksheet
        Dim lastsourcerow as Long
        Dim lastdestrow as Long
        Dim i as Long
    
        Set sourcesheet = Worksheets("HiddenSheet")
        Set destsheet = Worksheets("SNVReports")
    
        With sourcesheet
    
            lastsourcerow = .Cells(.Rows.Count, 1).End(xlUp).Row
    
            For i = 1 To lastsourcerow
    
                If .Cells(i, 12).Value = "SNV" Then
                    lastdestrow = destsheet.Cells(destsheet.Rows.Count, 1).End(xlUp).Row
                   .Range(.Cells(i, 1), .Cells(i, 6)).Copy destsheet.Cells(lastdestrow + 1, 1)
                End If
    
            Next
    
        End With
    
    End Sub