Excel VBA代码错误

我有以下的macros,加上0的身份证号码,直到他们是7个数字长。 我曾经使用过它无数次,它一直工作,直到今天,直到今天,它没有开始工作,代码部分For i = 1 To endrow - 1每次突出显示,我不能debugging的问题。 整个代码是。

 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 

不知道是什么导致了错误 – 但会提出另一种方法:

 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将单元格值视为string。 这是一个安全的方法,以确保零…

编辑:摆脱了最后一步。select显示它可以做到,一般是良好的做法,如在评论中指出的。