【发布时间】:2019-06-10 05:19:21
【问题描述】:
我正在用 VBA 编写一个简短的脚本,用于打印和比较各个单元格中的时间戳。代码工作正常,但是我对“ByRef 参数类型不匹配”的不一致感到困惑。我的代码如下。
Function nextrow()
With ActiveSheet
nextrow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
End Function
____
Private Sub buttonclick(nr As Integer)
With ActiveSheet
.Cells(nr, 2) = Now
If nr = 2 Then Exit Sub
dur = .Cells(nr, 2) - .Cells(nr - 1, 2)
.Cells(nr - 1, 3) = dur
End With
End Sub
____
Private Sub distract2()
nr = nextrow
If nr = 2 Then Exit Sub
buttonclick nr - 1
End Sub
如果您查看distract2,您会注意到我没有将nr 定义为整数,但即便如此,它也可以毫无问题地传递给buttonclick。
但是,当我从 nr 之后删除 -1 时,VBA 会引发 ByRef 错误。
两个问题:
- 有人知道为什么会这样吗?
-
dim nr as Integer好还是不好?
【问题讨论】:
-
您应该始终将
Option Explicit放在每个代码模块的顶部。你应该总是Dim你使用的每一个变量。除此之外,在buttonclick行之前尝试buttonclick (nr-1) to perform the calculation *before* passing anything tobuttonclickand see if that helps. If not, put in a linenr = nr -1`。 -
您的
function nextrow不返回值,即函数的定义。所以它实际上是一个潜艇。nr永远不会等于任何东西。 -
@Cindy,感谢您的提示。 @catcat,这是一个很好的观点。如果我改了,你觉得我还需要
dim nr吗?