为什么我的函数假定缺少参数?

eir*_*ude 4 forms excel vba excel-vba excel-2016

我有一个更新表单"LoadingInterface"的函数.该函数如下所示:

Private Sub updateLoadingBar(Optional tekst As String, Optional barOnePerc As Long, Optional barTwoPerc As Long)
    If Not IsMissing(tekst) Then
        LoadingInterface.Label1.Caption = tekst
    End If
    If Not IsMissing(barOnePerc) Then
        LoadingInterface.Bar.Width = barOnePerc * 1.68
        LoadingInterface.prosent.Caption = barOnePerc & "%"
        LoadingInterface.prosent.Left = barOnePerc * 1.68 / 2 - 6
    End If
    If Not IsMissing(barTwoPerc) Then
        LoadingInterface.SubBar.Width = barTwoPerc * 1.68
    End If
    LoadingInterface.Repaint
End Sub
Run Code Online (Sandbox Code Playgroud)

然后我调用这样的函数,期望它只更新文本字段,因为缺少其他两个参数.

Call updateLoadingBar(tekst:="Test")
Run Code Online (Sandbox Code Playgroud)

这适用于更新Label1,但不幸的是其他两个值也被更新 - 似乎不包括函数调用中的任何值使得VBA假设两个变量值为0.而且,似乎IsMissing函数没有检测到调用函数时两个值都缺失,这是一个更大的问题.使用F8逐步执行代码确认确实输入了所有if语句.

有没有什么办法让代码跳过我的函数两个最下面的if语句,如果提供的参数没有值barOnePercbarTwoPerc

QHa*_*arr 11

IsMissing 仅在参数声明为Variant时才有效.

我认为你不能有效地区分0和没有传递参数的Long.在这种情况下,您需要在签名中声明为Variant.如果需要,您可以稍后施放.

我想你可以设置默认值(不太可能的数字)并测试.注意:我建议这样做.这只是尖叫"Bug".

IsMissing:

IsMissing返回一个布尔值,指示是否已将可选的Variant参数传递给过程.

语法:IsMissing(argname)

必需的argname参数包含可选的Variant过程参数的名称.

备注:使用IsMissing函数检测在调用过程时是否提供了可选的Variant参数.如果没有为指定的参数传递值,则IsMissing返回True; 否则,返回False.

两种方法:

Option Explicit

Public Sub Test()
    RetVal
    RetVal2
End Sub

Public Function RetVal(Optional ByVal num As Long = 1000000) As Long

    If num = 1000000 Then

        MsgBox "No value passed"
        RetVal = num
    Else

        MsgBox "Value passed " & num
        RetVal = num
    End If

End Function


Public Function RetVal2(Optional ByVal num As Variant) As Long

    If IsMissing(num) Then

        MsgBox "No value passed"

    Else

        MsgBox "Value passed " & num
        RetVal2 = CLng(num)
    End If

End Function
Run Code Online (Sandbox Code Playgroud)

  • 啊,我不敢相信自从我上次做这样的事情以来我已经忘记了.或者它没有出现在我粗略的谷歌搜索中:P谢谢你指出它. (2认同)