数据过多时,Range(myRng).Copy会引发“对象_global失败的范围”

时间:2018-09-11 15:09:02

标签: excel vba

我有一个原始数据表,其中包含人员信息。每个人都被列为五类(五分位数)之一:

前20%,第四季度,第三季度,第二季度,后20%

我的宏在前20%中寻找每个人,将其选中,然后将其添加到名为myRng的范围中。将表格中前20%的所有人都添加到范围后,它将填充前20%的表格。

宏会为五个类别中的每一个进行迭代。

该宏适用于(超过约80行)但已崩溃并抛出Range of object _global failed(如果有太多数据)的数据样本。

如果我单击“调试”,则Range(myrng).Copy第25行会突出显示。

这是宏:

Sub populateTable(quintile As String, destinationTblName As String, sourceTblName As String)
    Application.CutCopyMode = False
    Worksheets("PRR Quintile Buckets").Activate
    Worksheets("PRR Quintile Buckets").Range("A1").Select

    Dim table As Range

'Clear table data
    Worksheets("PRR Quintile Buckets").Range(destinationTblName).Clear
    Worksheets("PRR Quintile Buckets").Range(destinationTblName).ClearContents
    Worksheets("PRR Quintile Buckets").Range(destinationTblName).Rows.Delete

'Fetch new data
    Worksheets("raw_data").Activate
    Set table = Sheets("raw_data").Range(sourceTblName)
    For Each cell In table.Columns(3).Cells
        If myRng = Empty And cell = quintile Then
            myRng = cell.Offset(, -1).Address(0, 0) & ":" & cell.Offset(, 5).Address(0, 0)
        ElseIf cell = quintile Then
            myRng = myRng & "," & cell.Offset(, -1).Address(0, 0) & ":" & cell.Offset(, 5).Address(0, 0)
        End If
    Next cell

'Prepare data for table insertion and then copy
    Worksheets("raw_data").Range(myRng).Copy
    Dim tbl As ListObject
    Set tbl = Worksheets("PRR Quintile Buckets").ListObjects.Item(destinationTblName)
    With Worksheets("macro_sandbox")
        .Activate
        .Range("a1").Select
        .Paste
        .Range(Selection, Selection.End(xlDown)).Select
        .Range(Selection, Selection.End(xlToRight)).Select
        Selection.Style = "Normal"
        Range("C1").Select
        Range(Selection, Selection.End(xlDown)).Select
        Selection.Style = "Percent"
        Selection.NumberFormat = "0.00%"
        .Range("a1").Select
        .Range(Selection, Selection.End(xlDown)).Select
        .Range(Selection, Selection.End(xlToRight)).Select

        For i = 0 To Selection.Rows.Count - 1
            tbl.ListRows.Add
        Next i

    End With
    Selection.Copy Destination:=Sheets("PRR Quintile Buckets"). _
        ListObjects(destinationTblName).Range.Cells(2, 1)
    Sheets("macro_sandbox").UsedRange.ClearContents
    Worksheets("macro_sandbox").Activate
    Worksheets("macro_sandbox").Range("A1").Select
End Sub

我认为可能是因为Range(rng1,rng2,...,rangN)包含太多范围。

或者也许是因为Range(myRng).Copy方法不能支持那么多选择。

任何想法都可能导致此问题吗?有没有更好的方法来填充表?

希望我可以附上工作簿,但它是机密的。如果需要,我可以尝试构建一个模拟工作簿。

谢谢。

0 个答案:

没有答案