如何解决VBA中的溢出错误?

时间:2020-01-24 16:46:34

标签: excel vba overflow

我必须分析一个非常大的数据文件,并获取一些数据并将其放入另一个工作表中,直到我大约有20,000行时,它才起作用,但是在那之后,它给了我一个溢出错误,我需要对它进行分析20万行,有可能吗?

Sub prueba()

Dim i As Double, j As Double, k As Double, l As Double
Dim i2 As Double
Dim lrow As Integer
Dim LastRow As Double


lrow = Cells(Rows.Count, 1).End(xlUp).Row
LastRow = Range("E" & Rows.Count).End(xlUp).Row

i = 1
While Sheet1.Cells(18, i) <> "Suma de Máximo"

    i = i + 1

Wend

j = 1
While Sheet1.Cells(18, j) <> "Suma de Stock"

    j = j + 1

Wend

k = 1
While Sheet1.Cells(18, k) <> "Sum of Mínimo"

    k = k + 1

Wend

If Sheet1.Cells(18, k) = "Sum of Mínimo" And Sheet1.Cells(18, j) = "Suma de Stock" Then

    For i2 = 18 To LastRow - 1

        If Sheet1.Cells(i2, k) <> Sheet1.Cells(i2, j) Then

            Sheet2.Cells(i2 - 17, 1) = Sheet1.Cells(i2, 1)
            Sheet2.Cells(i2 - 17, 2) = Sheet1.Cells(i2, 2)
            Sheet2.Cells(i2 - 17, 3) = Sheet1.Cells(i2, i)
            Sheet2.Cells(i2 - 17, 4) = Sheet1.Cells(i2, k)
            Sheet2.Cells(i2 - 17, 5) = Sheet1.Cells(i2, j)

        End If

    Next i2

End If

End Sub

2 个答案:

答案 0 :(得分:2)

Dim lrow As Integer

这是16位带符号整数类型,最大值为32,767(2 ^ 15-1):将其分配给32,768或更高版本时,它将立即溢出。任何工作表的行数都要多得多,这使Integer成为不适合用于存储工作表行号的数据类型。

请改用Long,它是32位有符号整数类型,最大值为2 ^ 31-1,大于Excel工作表的行数。

Double是一种浮点数据类型,对于行号使用没有太大意义。考虑使用有意义的名称而不是单字母变量,但是请注意,这些循环效率非常低:

k = 1
While Sheet1.Cells(18, k) <> "Sum of Mínimo"

    k = k + 1

Wend

需要快速查找包含特定内容的单元格时,请使用Range.Find

答案 1 :(得分:0)

替换:

Dim i As Double, j As Double, k As Double, l As Double
Dim i2 As Double
Dim lrow As Integer
Dim LastRow As Double

具有:

Dim i As Long, j As Long, k As Long, l As Long
Dim i2 As Long
Dim lrow As Long
Dim LastRow As Long