选择要复制的范围时出错

时间:2013-11-08 09:34:21

标签: excel-vba vba excel

我需要选择一个特定的范围来复制每个for循环的变量起点和终点,所以使用了Range(Cells(x,x),Cells(y,y).Select方法。 这会给我一个错误:

For i = 1 To 40
        Worksheets("BloombergData").Select
        Worksheets("BloombergData").Range(Cells(5, 2 + 11 * (i - 1)), Cells(4 + Worksheets("Lookup").Cells(i + 1, 3).Value, 11 + 11 * (i - 1))).Select
        Selection.Copy
        Worksheets("Data_Rearranged").Range(Cells(6 + Worksheets("Lookup").Cells(i, 3).Value, 4), Cells(5 + Worksheets("Lookup").Cells(i + 1, 3).Value, Data_Columns + 3)).Select
        Selection.Paste
    Next i

即使我简化了细胞功能,它仍然无效。我试过这个测试,它给了我同样的错误:

Worksheets("BloombergData").Range(Cells(1, 1), Cells(2, 1)).Select
Selection.Copy

只有当我将实际单元格放在Range中时才会起作用,即Range(“A1”)

但我的范围是可变的,所以我需要找到一些选择变量范围的方法。

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

很明显,你会得到错误。您的单元格对象未完全合格。请注意下面代码中Cells对象之前的DOT。

BTW我还没有测试2 + 11 * (i - 1)评估的内容。因此,如果评估为不可接受的数字,则代码将再次失败。

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

为了便于理解,您还可以将代码分解为此。稍后调试它会很容易:)

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