0

我有以下宏,它在一串数字的开头添加多个零,直到数字总共有 7 位数字。目前它只执行 A 列,我希望它为我选择的任何列运行宏,因此我不必总是剪切和粘贴以及重新剪切和粘贴运行它所需的所有列。有任何想法吗?

Sub AddZeroes1()
'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
4

3 回答 3

2

您可以通过将目标更改为选择而不是特定列来更新任意数量的列。(由 t.thielemans 建议)

尝试这个:

Sub AddZeroesToSelection()
     Dim rng As Range
     Dim cell As Range

     Set rng = Selection
     rng.NumberFormat = "@"

     For Each cell In rng
        Do While Len(cell.Value) < 7
          cell.Value = "0" & cell.Value
        Loop
     Next cell

End Sub
于 2013-08-21T16:17:37.813 回答
1

仅更改 MyCol 行:

Sub AddZeroes1()
Dim cl As Range
Dim i As Long, endrow As Long
Dim MyCol As String
MyCol = "A"
Application.ScreenUpdating = False
    Columns(MyCol & ":" & MyCol).NumberFormat = "@"
    endrow = ActiveSheet.Range(MyCol & "1048576").End(xlUp).Row
    For i = 1 To endrow - 1
        Set cl = Range(MyCol & i)
        With cl
            Do While Len(.Value) < 7
                .Value = "0" & .Value
            Loop
        End With
    Next i
Application.ScreenUpdating = True
End Sub

未测试

于 2013-08-21T16:04:47.283 回答
1

从你的问题:

它在一串数字的开头添加多个零,直到该数字总共有 7 位数字

如果您只是希望数字显示前导 0,直到数字长 7 位,您可以使用自定义格式:0000000

例如:

    123
   5432
     26
9876543

选择单元格->右键单击->设置单元格格式->自定义->输入“0000000”(无引号)->确定

现在它们应该以前导 0 出现:

0000123
0005432
0000026
9876543

如果它必须是一个宏,那么这应该工作:

Sub AddZeroes1()

    Selection.NumberFormat = "0000000"

End Sub
于 2013-08-21T16:20:04.630 回答