我在 Excel 中以垂直选择的方式循环遍历一些单元格,然后将该单元格作为参数传递给过程。
我已经这样做了,所以我没有在代码中两次获得 ProcessCells 的内容,一次在 while 循环中,第二次在 For 循环中。
如果我尝试在 for 循环中写出单元格的值,它就会起作用。 如果我将 ProcessCells 过程的内容放入 for 循环中,它也可以工作。
但是如果我尝试将其作为参数传递到 ProcessCells 中,则会收到错误
'Object Required'
这是代码,如果您想查看一下:
Sub loopThroughCells()
Dim c As Range
Dim autoSelect As String
Dim X, Y As Integer
autoSelect = Cells(3, 2).Value
If StrComp(autoSelect, "Y") = 0 Then
Y = 5
X = 4
While Not IsEmpty(Cells(Y, X).Value)
ProcessCells (Cells(Y, X))
Y = Y + 1
Wend
Else
For Each c In Selection
ProcessCells (c)
Next c
End If
End Sub
Sub ProcessCells(ce As Range)
End Sub
怎么样
Cells(n,m)
不同于
c In Selection
?
错误发生在 For 循环中,但不会发生在 while 循环中。
最佳答案
您应该这样做:
Option Explicit
Sub TestMe()
Dim c As Range
For Each c In Selection
Call ProcessCells(c)
Next c
End Sub
Sub ProcessCells(ce As Range)
End Sub
您应该使用call
来引用,因为括号中有一个参数。
或者像这样,如果您不喜欢调用
:
Option Explicit
Sub TestMe()
Dim c As Range
For Each c In Selection
ProcessCells c
Next c
End Sub
Sub ProcessCells(ce As Range)
End Sub
加上您的代码的小版本。像这样进行声明:
Dim X as Long, Y As long
在您的代码中,X 被声明为变体,并且整数比 long 更慢且更小 - Why Use Integer Instead of Long?
这里有一些很好的解释何时将参数放在括号中以及何时使用 call
- How do I call a VBA Function into a Sub Procedure
关于vba - 在选择的单元格中循环时对象需要错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716830/