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

我试图创buildExcel模板(数据量将有所不同的情况下),它看起来像这样:

在这里输入图像说明

在每一个连续的行都是“客户”,我想在每一个奇数行“总帐”。 基本上应该把“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 

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

非常感谢!

如果一个命令开始. .Cells它希望在一个声明像…

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

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

不是说在你的模块的顶部使用Option Explicit来强制声明每个variables(你错过了声明i As Long )是一个好主意。

你的代码可以减less到…

 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 

只需循环第2步即可获取索引器variables中的其他行。

 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