VBA ByRef 参数类型不匹配不一致?

VBA ByRef argument type mismatch is inconsistent?

我正在 VBA 中编写一个简短的脚本,用于打印和比较各个单元格中的时间戳。代码运行良好,但我对 "ByRef arugement type mismatch" 的不一致感到困惑。我的代码如下。

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 错误。

两个问题:

由于您正在处理行,我建议使用 Long 而不是 Integer。您收到该错误是因为在 Private Sub buttonclick(nr As Integer) 中,它需要 Integer 而您传递的是 Variant

Private Sub buttonclick(nr As Integer)更改为Private Sub buttonclick(nr As Long)

并使用这个

Private Sub distract2()
    Dim nr As Long
    Dim nVal As Long

    nr = nextrow

    If nr = 2 Then Exit Sub

    nVal = nr - 1

    buttonclick nVal
End Sub

However, when I remove -1 from after nr, VBA throws a ByRef error. Two questions: Does anyone know why this happens? Is it better to dim nr as Integer or not?

当您保留 -1 时,它会将值减去 1,结果是 Integer 类型,因此您不会收到错误。如果 nr104857 那么它会报错。 Interesting Read

是的,最好将变量调暗为相关数据类型。但是,在您的情况下,它应该是 Long 而不是上面提到的 Integer

你的完整代码可以写成

Option Explicit

Private Sub distract2()
    Dim nr As Long
    Dim nVal As Long

    nr = nextrow

    If nr = 2 Then Exit Sub

    nVal = nr - 1

    buttonclick nVal
End Sub

Function nextrow() As Long
    With ActiveSheet
        nextrow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With
End Function

Private Sub buttonclick(nr As Long)
    With ActiveSheet
        .Cells(nr, 2) = Now
        If nr = 2 Then Exit Sub
        .Cells(nr - 1, 3) = .Cells(nr, 2) - .Cells(nr - 1, 2)
    End With
End Sub