VBA For Excel内存不足错误 - 我该如何避免这种情况?

时间:2015-12-11 15:44:31

标签: excel vba excel-vba out-of-memory large-data

我正在使用VBA宏来比较数据库之间的某些值,以更新某些默认设置与推荐设置。我的工作簿中有3张(AV,AK和AP),分别有大约16,000,660和9,000行。每张纸也有6-9列。

当我尝试运行此宏时,我收到“Out of Memory”错误:

Sub DefaultsMacro()

Dim AVsheet As Worksheet
Set AVsheet = ThisWorkbook.Sheets("AIV export")
Dim AKsheet As Worksheet
Set AKsheet = ThisWorkbook.Sheets("AIK export")
Dim APsheet As Worksheet
Set APsheet = ThisWorkbook.Sheets("AIP export")
'Set all of the sheets to variable names for ease of use.

LengthAv = AVsheet.Cells(Rows.Count, 1).End(xlUp).Row
LengthAv = LengthAv - 1

LengthAK = AKsheet.Cells(Rows.Count, 1).End(xlUp).Row
LengthAK = LengthAK - 1

LengthAP = APsheet.Cells(Rows.Count, 1).End(xlUp).Row
LengthAP = LengthAP - 1
'Set the length of each spreadsheet (# of rows)

For r1 = 5 To LengthAv
    If AVsheet.Cells(r1, 2) <> "" And AVsheet.Cells <> "<NULL>" Then 'Skip over null and empty rows
        AVsheet.Cells(r1, 8) = 0 'Place zeros in case null isn't treated as a zero
        AVsheet.Cells(r1, 9) = 0

        For AIKs = 1 To 99999 'Loop around until there is a non-Null value meaning we're at the next PV
            x = r1 + AIKs
            If AVsheet.Cells(x, 2) <> "" Then
                Exit For
            End If
        Next AIKs
        'After this loop, AIKs will be the # of AIKs that this PV is used in.
        PVRows = r1 + AIKs - 1 'This is the last row that this PV occupies range of r1 to PVRows will be all of the PV's rows

        For x = r1 To PVRows
            AVsheet.Cells(x, 7) = 0
        Next x

        For r2 = 5 To LengthAP
            If APsheet.Cells(r2, 3) = AVsheet.Cells(r1, 1) Then 'If there is an instance of the profileVariable
                AVsheet.Cells(r1, 8) = AVsheet.Cells(r1, 8) + 1
                If APsheet.Cells(r2, 5) <> AVsheet.Cells(r1, 3) Then 'If the default value and recommended value are not equal
                    AVsheet.Cells(r1, 9) = AVsheet.Cells(r1, 9) + 1
                End If
            End If
        Next r2
    End If
Next r1
End Sub

当我调试时,导致内存错误的行(根据调试工具)是:

If AVsheet.Cells(r1, 2) <> "" And AVsheet.Cells <> "<NULL>" Then 'Skip over null and empty rows

我对excel还不是很熟悉VBA(在1-2天内自学这么多)。有没有办法可以改变我的代码,以免出现Out of Memory错误?

谢谢!

0 个答案:

没有答案