rg.NumberFormat =“ 0”显示对象变量或带有块变量的未设置错误VBA

时间:2018-06-25 08:06:25

标签: excel excel-vba vba

代码:

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


Excel栏:
enter image description here

这是用于用前导零填充单元格中值的代码。它仅工作一次,但此后不工作。我没有更改代码。
错误:
enter image description here

1 个答案:

答案 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