我有以下宏,它在一串数字的开头添加了一些零,直到该数字总共有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
答案 0 :(得分: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
答案 1 :(得分: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
未经过测试
答案 2 :(得分:1)
从你的问题:
它在一串数字的开头添加了一些零,直到该数字总共有7位
如果您只是希望数字显示前导0,直到数字长度为7位,您可以使用自定义格式:0000000
例如:
123
5432
26
9876543
选择单元格 - &gt;右键单击 - &gt;格式化单元格 - &gt;自定义 - &gt;输入“0000000”(无引号) - &gt;行
现在它们应该以前导0出现:
0000123
0005432
0000026
9876543
如果必须是宏,那么这应该有效:
Sub AddZeroes1()
Selection.NumberFormat = "0000000"
End Sub