由于溢出错误,无法在整个工作簿中 运行 Excel 宏循环

Not able to run an Excel Macro loop throughout the workbook due to overflow error

我有 7 个 sheet 超过 70,000 个条目;我在每个 sheet 的单独列中对每个唯一属性求和。

虽然宏在单个 sheet 上运行良好,但我很难在每个 sheet 上循环我的宏,并且出现溢出错误。

我在想,要么查询的总和不适合 Excel,要么我需要以某种方式将我的输出重新定义为长整数。

Sub Summation()

Dim WS_Count As Integer
Dim I As Integer

WS_Count = ActiveWorkbook.Worksheets.Count

For X = 1 To WS_Count

    Sheets(X).Select

     Dim total As Variant

     Dim attribute As String
     Dim data_last_row As Variant
     Dim attribute_last_row As Variant

     Range("I1").Value = "Unique Attribute"
     Range("L1").Value = "Total"

     data_last_row = Cells(Rows.Count, "A").End(xlUp).Row

     For I = 2 To data_last_row
         attribute = ws.Cells(I, 1)
         total = Cells(I, 7) + total
         attribute_last_row = Cells(Rows.Count, "I").End(xlUp).Row
         If Cells(I + 1, 1) <> attribute Then
             Cells(attribute _last_row + 1, 9) = attribute 
         End If
         Cells(attribute _last_row + 1, 12) = total        
     Next I

Next X

End Sub

我也试过 For Each ws In Worksheets 并将我的单元格定义为 ws,但是 在随后的每个 sheet 中输出都偏离了,基本上复制了第一个 sheet 中宏的结果。

是否有其他方法,或者 Excel 根本不适合处理这么多数据?

现在应该可以工作了。

attribute 不应声明为变量,因为它是关键字

attributes _last_row 中间有一个 space。可能是打字错误,但请注意。

Sub Summation()

Dim WS_Count As Integer
Dim I As Long
Dim ws As Worksheet

WS_Count = ActiveWorkbook.Worksheets.Count

For X = 1 To WS_Count

    Set ws = Sheets(X)

    Dim total As Variant


    Dim attributes As String
    Dim data_last_row As Variant
    Dim attributes_last_row As Variant

    ws.Range("I1").Value = "Unique Attribute"
    ws.Range("L1").Value = "Total"

    data_last_row = Cells(ws.Rows.Count, "A").End(xlUp).Row

    For I = 2 To data_last_row
        attributes = ws.Cells(I, 1)
        total = ws.Cells(I, 7) + total
        attributes_last_row = ws.Cells(ws.Rows.Count, "I").End(xlUp).Row
        If Cells(I + 1, 1) <> attributes Then
             ws.Cells(attributes_last_row + 1, 9) = attributes
        End If

        ws.Cells(attributes_last_row + 1, 12) = total

    Next I

Next X

End Sub