2013-01-21 130 views
0

我有以下宏,它将0添加到ID号码中,直到它们是7个数字为止。我以前用过无数次,直到今天它一直运行无误,并且代码For i = 1 To endrow - 1的部分每次都突出显示,我无法调试问题。整个代码是。Excel VBA代码错误

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 
+4

** endrow **在停止点的价值是多少?另外,如果格式仅用于显示目的,那么整个例程可以用'Columns(“A:A”)替换。NumberFormat =“0000000”' – SeanC

+0

Endrow部分是告诉它在最后一行停止,通常它会减少一个额外的行并添加一个只有7个0的单元。 -1告诉它在最后一个单元停止。 – user1958651

+0

当代码被突出显示以指示错误时,** endrow **在该点的值是什么? – SeanC

回答

3

不知道是什么原因造成的错误 - 但建议用另一种方法:

sub addZeros() 
    Application.ScreenUpdating = False 
    ' start at row 2 since OP said there's a header row 

    Dim c as Range 
    for each c in Range("A2", [A2].End(xlDown)) 
    c.Value = "'" & Format(c.Value, "00000000") 
    next c 
    Application.ScreenUpdating = True 
end sub 

有点更紧凑...

请注意,我加入“'”撇号使Excel将单元格值视为字符串。这是一个安全的方式,以确保零...

编辑:摆脱最后。选择显示它可以完成,并且一般是良好的做法,如评论中指出的。

+0

+1:用于摆脱大部分.Select和Active *引用 – RBarryYoung

+0

谢谢@RBarryYoung。我可以用''范围内的每个c(“A2”,[A2] .End(xlDown))''来摆脱最后的选择。这将会更短,更干净。 – Floris