VBA - 无效或不合格的参考错误

时间:2017-09-08 12:35:47

标签: excel vba excel-vba loops

我正在尝试创建excel模板(数据量因情况而异),它看起来像这样:

enter image description here

在每一个偶数行都是“客户”,我想把每一个奇怪的行放在“Ledger”中。基本上它应该将“Ledger”放到每个奇数行,直到C列中有数据。我有这个代码:

'========================================================================
' INSERTING LEDGERS for every odd row (below Customer)
'========================================================================

Sub Ledgers()

    Dim rng As Range
    Dim r As Range
    Dim LastRow As Long

    LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
    Set rng = .Range("C5:C" & LastRow)

    For i = 1 To rng.Rows.Count
        Set r = rng.Cells(i, -2)
        If i Mod 2 = 1 Then
            r.Value = "Ledger"
        End If

    Next i

End Sub

但它给我一个错误信息无效或不合格的参考。你能告诉我,我有错误吗?

非常感谢!

2 个答案:

答案 0 :(得分:6)

如果某个命令以.开头,例如.Cells,则它应该在with语句中,如...

With Worksheets("MySheetName")
    LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
    Set rng = .Range("C5:C" & LastRow)
End With

因此,您需要指定预期单元格所在的工作表的名称。

不是在模块顶部使用Option Explicit来强制声明每个变量(您错过声明i As Long)这不是一个好主意。

您的代码可以缩减为......

Option Explicit 

Public Sub Ledgers()
    Dim LastRow As Long
    Dim i As Long

    With Worksheets("MySheetName") 
        LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row

        'make sure i starts with a odd number
        'here we start at row 5 and loop to the last row
        'step 2 makes it overstep the even numbers if you start with an odd i
        'so there is no need to proof for even/odd
        For i = 5 To LastRow Step 2 
            .Cells(i, "A") = "Ledger" 'In column A
            '^ this references the worksheet of the with-statement because it starts with a `.`
        Next i
    End With
End Sub

答案 1 :(得分:0)

只需循环第2步,即可获得索引器变量中的每一行。

Sub Ledgers()
    Dim rng As Range
    Dim LastRow As Long

    LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "C").End(xlUp).Row
    Set rng = ActiveSheet.Range("C5:C" & LastRow)

    For i = 1 To LastRow step 2
        rng.Cells(i, 1) = "Ledger" 'In column A
    Next i
End Sub