【问题标题】:VBA ByRef argument type mismatch is inconsistent?VBA ByRef 参数类型不匹配不一致?
【发布时间】: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 to buttonclickand see if that helps. If not, put in a line nr = nr -1`。
  • 您的function nextrow 不返回值,即函数的定义。所以它实际上是一个潜艇。 nr 永远不会等于任何东西。
  • @Cindy,感谢您的提示。 @catcat,这是一个很好的观点。如果我改了,你觉得我还需要dim nr吗?

标签: excel vba byref


【解决方案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

【讨论】:

  • 感谢您的文章,它真的为我澄清了一些事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多