0

我有以下宏将 0 添加到 ID 号,直到它们长为 7 个数字。我之前已经使用过无数次,它一直都能正常工作,直到今天它开始无法正常工作,并且For 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
4

1 回答 1

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 将单元格值视为字符串。这是确保零保持不变的安全方法...

编辑:去掉最后一个 .Select 以显示它可以完成,并且通常是评论中指出的好习惯。

于 2013-01-21T17:28:24.127 回答