代码:
Option Explicit
Sub LeadingZeros()
Dim cel As Range
Dim rg As Range
Dim mx As Integer: mx = 0
Dim cl As Variant
For Each cl In Selection
If Len(cl) > mx Then mx = Len(cl)
Next
rg.NumberFormat = "0" 'this is showing error
Dim i As Integer
For i = 0 To mx - 2
If mx = 1 Then Exit Sub
rg.NumberFormat = rg.NumberFormat & "0"
Next
End Sub
答案 0 :(得分:1)
您必须将变量rg
分配给一个范围。这是通过单词Set
完成的。在此示例中,rg
被分配给A1:A5
,它可以进一步工作:
Sub LeadingZeros()
Dim cel As Range
Dim rg As Range
Dim mx As Integer: mx = 0
Dim cl As Variant
For Each cl In Selection
If Len(cl) > mx Then mx = Len(cl)
Next
Set rg = Range("A1:A5")
rg.NumberFormat = "0" 'this is showing error
Dim i As Integer
For i = 0 To mx - 2
If mx = 1 Then Exit Sub
rg.NumberFormat = rg.NumberFormat & "0"
Next
End Sub