0

我有以下代码将零添加到一个数字,直到该数字的总长度为 7 位。到目前为止它工作得很好,代码是:

Sub AddZeroes()
'Declarations
Dim i As Integer, j As Integer, endrow As Long
'Converts the A column format to Text format
Application.ScreenUpdating = False
Columns("A:A").Select
Selection.NumberFormat = "@"
'finds the bottom most row
endrow = ActiveSheet.Range("A1").End(xlDown).Row
'selects the top cell in column A
ActiveSheet.Range("A1").Select

'loop to move from cell to cell
For i = 1 To endrow - 1
            'Moves the cell down 1. Assumes there's a header row so really starts at row 2
            ActiveCell.Offset(1, 0).Select
            'The Do-While loop keeps adding zeroes to the front of the cell value until it     hits     a length of 7
Do While Len(ActiveCell.Value) < 7
                            ActiveCell.Value = "0" & ActiveCell.Value
            Loop
Next i
Application.ScreenUpdating = True
End Sub

代码循环遍历 A 列,如果一个数字的总数不超过 7 个,则在开头添加 0。错误出现在代码部分

FOR I = 1 TO ENDROW - 1

我似乎无法弄清楚出了什么问题。这部分告诉宏,一旦它到达列表的末尾,就可以找到空白并向上移动 1,因此它会停在最后一个数字上,并且一直工作到今天。

4

1 回答 1

1

您正在使用i可能导致该变量溢出的整数值。

尝试这个:

Option Explicit
Sub AddZeroes()
'Declarations
Dim cl As Range
Dim i As Long, endrow As Long

    Application.ScreenUpdating = False
        'Converts the A column format to Text format
        Columns("A:A").NumberFormat = "@"
        'finds the bottom most row
        endrow = ActiveSheet.Range("A1048576").End(xlUp).Row
        '## Or, for Excel 2003 and prior: ##'
        'endrow = ActiveSheet.Range("A65536").End(xlUp).Row

        'loop to move from cell to cell
        For i = 1 To endrow - 1
            Set cl = Range("A" & i)
            With cl
            'The Do-While loop keeps adding zeroes to the front of the cell value until it     hits     a length of 7
                Do While Len(.Value) < 7
                    .Value = "0" & .Value
                Loop
            End With
        Next i
    Application.ScreenUpdating = True
End Sub
于 2013-05-08T18:03:58.403 回答