gpt4 book ai didi

vba - 使用 .Cells 时出现无效或不合格的引用错误

转载 作者:行者123 更新时间:2023-12-02 05:06:03 24 4
gpt4 key购买 nike

我正在尝试创建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

但它给了我一个错误消息无效或不合格的引用。您能告诉我哪里有错误吗?

非常感谢!

最佳答案

如果命令以 . 开头(例如 .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

关于vba - 使用 .Cells 时出现无效或不合格的引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46116741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com