Error in selecting range to copy

后端 未结 1 1934
无人共我
无人共我 2021-01-26 04:55

I need to select a specific range to copy with variable start and end point at each for loop, so used the Range(Cells(x,x), Cells(y,y).Select method. This would give me an error

相关标签:
1条回答
  • 2021-01-26 05:26

    It is but obvious that you will get the error. Your Cells Object is not fully Qualified. Notice the DOT before the Cells Object in the code below.

    BTW I have not tested what 2 + 11 * (i - 1) evaluates to. So if evaluates to an unacceptable number then the code will fail again.

    Sub Sample()
        Dim ws As Worksheet
    
        Set ws = ThisWorkbook.Worksheets("BloombergData")
    
        With ws
            For i = 1 To 40
                .Range(.Cells(5, 2 + 11 * (i - 1)), .Cells(4 + Worksheets("Lookup").Cells(i + 1, 3).Value, 11 + 11 * (i - 1))).Copy
                '
                '~~> Rest of the code
                '
            Next
        End With
    End Sub
    

    INTERESTING READ

    For easy understanding you could also break down your code to this. It will become easy to debug it later :)

    Sub Sample()
        Dim ws As Worksheet
        Dim r1 As Long, c1 As Long
        Dim r2 As Long, c2 As Long
    
        Set ws = ThisWorkbook.Worksheets("BloombergData")
    
        With ws
            For i = 1 To 40
                r1 = 5
                c1 = 2 + 11 * (i - 1)
    
                r2 = 4 + Worksheets("Lookup").Cells(i + 1, 3).Value
                c2 = 11 + 11 * (i - 1)
    
                .Range(.Cells(r1, c1), .Cells(r2, c2)).Copy
    
                '
                '~~> Rest of the code
                '
            Next
        End With
    End Sub
    
    0 讨论(0)
提交回复
热议问题