VBA - 无效或不合格的引用错误

Srp*_*pic 5 excel vba loops excel-vba

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

在此输入图像描述

每一个偶数行都是"客户",我想把每一个奇怪的行放在"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
Run Code Online (Sandbox Code Playgroud)

但它给我一个错误消息无效或不合格的引用.你能告诉我,我有错误吗?

非常感谢!

Pᴇʜ*_*Pᴇʜ 7

如果命令以.类似于.Cells它期望的with语句开头,那么...

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

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

并不是说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
Run Code Online (Sandbox Code Playgroud)