2013-05-08 108 views
0

我有以下代码将零加到数字上,直到数字总共有7位数字为止。现在是工作的罚款,直到,代码: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 

代码循环的A柱,如果一些没有7点总数将其添加至0开始。错误出现在代码部分

FOR I = 1 TO ENDROW - 1 

我似乎无法弄清楚什么是错的。这部分告诉宏,一旦它到达列表的末尾以找到空格并向上移动1,它就会停在最后一个数字上,直到今天。

+0

所以有什么错误? – Satya 2013-05-08 17:50:15

+0

我补充说到底 – user2119980 2013-05-08 17:52:21

+0

是什么错误?你是否收到特定的错误信息? – 2013-05-08 17:57:18

回答

1

您使用的整数值为i,这可能会导致该变量发生溢出。

试试这个:

Option Explicit 
Sub AddZeroes() 
'Declarations 
Dim cl As Range 
Dim i As Long, endrow As Long 

    Application.ScreenUpdating = False 
     'Converts the A column format to Text format 
     Columns("A:A").NumberFormat = "@" 
     'finds the bottom most row 
     endrow = ActiveSheet.Range("A1048576").End(xlUp).Row 
     '## Or, for Excel 2003 and prior: ##' 
     'endrow = ActiveSheet.Range("A65536").End(xlUp).Row 

     'loop to move from cell to cell 
     For i = 1 To endrow - 1 
      Set cl = Range("A" & i) 
      With cl 
      'The Do-While loop keeps adding zeroes to the front of the cell value until it  hits  a length of 7 
       Do While Len(.Value) < 7 
        .Value = "0" & .Value 
       Loop 
      End With 
     Next i 
    Application.ScreenUpdating = True 
End Sub 
+0

这正是导致它的原因,非常感谢您的帮助。 – user2119980 2013-05-08 18:05:49

+1

很高兴工作!请注意其他代码的一些修订。尽可能避免像“Select”和“ActiveCell”这样的事情(99.9%的时间)。 :)通常这些构造根本就没有必要。 – 2013-05-08 18:07:57