COde中的宏错误

时间:2013-01-25 15:54:02

标签: excel excel-vba vba

我有一个宏为列a中的每个数字添加零,直到数字中总共有7个数字,它一直工作到今天我在行中得到错误For1 = i = 1 To endrow = -1,我无法弄清楚它的含义。

代码是

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

2 个答案:

答案 0 :(得分:2)

i可能已达到整数的上限(32767)。 Row会返回Long,因此i应该是Long,例如EndRow

Dim i As Long

答案 1 :(得分:0)

我重写了你的代码:

Sub test()
    Dim c As Range, rngTarget As Range
    Set rngTarget = Range("A:A").SpecialCells(xlCellTypeConstants, xlNumbers)
    rngTarget.NumberFormat = "@"
    For Each c In rngTarget
        c.Value = Left(c.Value & "0000000", 7)
    Next c
End Sub

更清晰,更快。