Excel 代码行中的宏错误
我有一个宏,将a列中的每个数字加上零,直到数字中有7个总数字,直到今天为止,它工作正常,我在1=I=1到endrow=-1的行中得到一个错误,我无法理解它的含义 代码是Excel 代码行中的宏错误,excel,vba,Excel,Vba,我有一个宏,将a列中的每个数字加上零,直到数字中有7个总数字,直到今天为止,它工作正常,我在1=I=1到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(
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
我可能已经达到了整数32767的上限。行返回Long,所以我应该是Long,就像EndRow一样
只要我重新编写了您的代码,我就会:
Sub test()
Dim c As Range, rngTarget As Range
Set rngTarget = Range("A:A").SpecialCells(xlCellTypeConstants, xlNumbers)
rngTarget.NumberFormat = "@"
For Each c In rngTarget
c.Value = Left(c.Value & "0000000", 7)
Next c
End Sub
更清晰更快。那么我该如何修复它呢?到目前为止,我已经用过几十次了。我只用了10行就试过了,但它仍然有效。我正试图在即时窗口中看到这个问题。按照iDevelop的建议,将整数声明更新为Long。您可能会发现这是获取结束行的更好方法:endrow=ActiveSheet.CellsRows.Count,1.EndxlUp.row