3

以下代码将按照我想要的方式正确格式化我的模板。但是,如果模板为空并且用户点击工作表上的准备上传按钮,我将收到溢出错误 6。有没有办法消除导致此错误的原因?

    Sub PrepForUpload()

Dim cel As Range, rng As Range

Set rng = Range("A2", Range("A65536").End(xlUp))

For Each cel In rng

    If cel.Value = "" Then

        If cel.Offset(, 2).Value = "" Then
            cel.EntireRow.Delete

        End If

    End If

    Next cel

Dim rowNumber As Integer
With Sheets("Initiatives")

If Len(.Cells(2, 1)) = 0 Then

rowNumber = .Cells(2, 1).End(xlDown).End(xlDown).Row + 1

Else: rowNumber = .Cells(2, 1).End(xlDown).Row + 1

End If

.Rows(rowNumber & ":" & .Rows.Count).Clear

End With


End Sub

调试指向以下行作为问题:

rowNumber = .Cells(2, 1).End(xlDown).End(xlDown).Row + 1

谢谢

瑞安

4

3 回答 3

10

你得到一个溢出,因为Integer在 VBA 中是一个 16 位有符号数(最大值为 32767)。无论 excel 的版本如何,您至少有 65535 行,如果您使用 XLSX 文件格式,则可能更多。您需要更改rowNumberLong

而且您还必须围绕空白工作表场景编写代码。当您调用此行时:

rowNumber = .Cells(2, 1).End(xlDown).End(xlDown).Row + 1

并且工作表为空白,.End(xlDown)将返回工作表中可能的最后一行,在 Excel 2010(和 Excel 2007)的情况下为 1048576。一旦更改rowNumber为 a Long,您将不再收到溢出错误,但您会遇到这条线的一个问题:

.Rows(rowNumber & ":" & .Rows.Count).Clear

这是因为您试图选择一个不存在的范围(第 1048577 行)(因此类型不匹配)。您需要添加一行代码来解决这种情况。最初检查空白工作表,或检查行 > 1048576。

最简单的做法是添加一行来检查:

If rowNumber <= 1048576 Then
    .Rows(rowNumber & ":" & .Rows.Count).Clear
End If
于 2012-09-27T15:13:57.530 回答
0

更改rowNumberLong然后添加1&或使用CLng以消除“类型不匹配”错误。

rowNumber = CLng(.Cells(2, 1).End(xlDown).End(xlDown).Row + 1)

或者

rowNumber = .Cells(2, 1).End(xlDown).End(xlDown).Row + 1&
于 2012-09-27T15:32:11.267 回答
0

您能告诉我们您的数据在 A 列中的样子吗?您也可以尝试此代码,该代码在尝试获取行号之前测试行数

Dim cel As Range, rng As Range

If Application.WorksheetFunction.CountA(Columns(1)) <= 1 Then
    MsgBox "No lines"
    Exit Sub
End If

Set rng = Range("A2", Cells(Rows.Count, 1).End(xlUp))

For Each cel In rng

    If Len(cel.Value) = 0 Then

        If Len(cel.Offset(, 2).Value) = 0 Then cel.EntireRow.Delete

    End If

Next cel

Dim rowNumber As Long

With Sheets("Initiatives")

    If Application.WorksheetFunction.CountA(.Columns(1)) <= 1 Then
        MsgBox "No lines in sheet Initiative"
        Exit Sub
    End If


If Len(.Cells(2, 1)) = 0 Then

    rowNumber = .Cells(2, 1).End(xlDown).End(xlDown).Row + 1

    Else: rowNumber = .Cells(2, 1).End(xlDown).Row + 1

End If

.Rows(rowNumber & ":" & .Rows.Count).Clear

End With
于 2012-09-27T16:10:39.510 回答