[英]Why does this VBA code give me an Object Required error?
I have the following code in an Excel macro:我在 Excel 宏中有以下代码:
Dim cellRange As range
Dim cell As range
Dim cellFormula As String
Dim yearCells As New Collection
For Each cellRange In ranges
For Each cell In cellRange.Cells
cellFormula = GetCellFormula(cell)
If (cellFormula = formulaYears) Then
yearCells.Add (cell)
End If
Next
Next
Where ranges
is a Collection
object holding many Range objects.其中ranges
是一个包含许多 Range 对象的Collection
对象。
When I run the code, I get an "Object required" error on the line For Each cellRange In ranges
.当我运行代码时,我在For Each cellRange In ranges
行上收到“需要对象”错误。 Why is this?为什么是这样? After all, cellRange
is declared as an object, ie Dim cellRange As range
.毕竟, cellRange
被声明为一个对象,即Dim cellRange As range
。 If I convert the code to a For
loop, I have the same error on a line:如果我将代码转换为For
循环,我会在一行中出现相同的错误:
Set cellRange = ranges(i)
BTW, my VBA IDE insists on range
always having a lower case initial letter.顺便说一句,我的 VBA IDE 坚持range
始终具有小写首字母。 When I type Range
the editor "corrects" it to range
.当我输入Range
,编辑器将其“更正”为range
。 Yet other code using range
objects works fine.然而其他使用range
对象的代码工作正常。
The answer lays in the way you populate your collection I'm sure.我敢肯定,答案在于您填充收藏的方式。 For example see the following:例如,请参见以下内容:
Sub Test()
Dim ranges As New Collection
Dim rng1 As Range, rng2 As Range, rng3 As Range
Dim cellRange As Range, cell As Range
Set rng1 = Range("A1:A3")
Set rng2 = Range("B1:B3")
Set rng3 = Range("C1:C3")
ranges.Add rng1
ranges.Add rng2
ranges.Add rng3
For Each cellRange In ranges
Debug.Print cellRange.Address
For Each cell In cellRange
Debug.Print cell.Address
Next cell
Next
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.