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

时间:2019-01-16 06:43:04

标签: excel vba byref

我正在VBA中编写一个简短的脚本,该脚本可以打印并比较各个单元格中的时间戳。该代码工作正常,但是我对“ ByRef arugement类型不匹配”的不一致感到困惑。我的代码在下面。

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还是更好?

1 个答案:

答案 0 :(得分:1)

由于您正在处理行,因此建议您使用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
  

但是,当我从nr之后删除-1时,VBA会抛出ByRef错误。   两个问题:   有谁知道为什么会这样吗?   将nr设置为Integer是否更好?

当您保留-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