0

ID 番号が 7 桁になるまで 0 を追加する次のマクロがあります。これまで数え切れないほど使用してきましたが、今日は機能しなくなり、コードの一部が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 に答える