无法在循环中将参数传递给函数调用

时间:2019-04-29 12:58:31

标签: excel vba

我有一个for循环,该循环使用一些参数来调用外部函数。每当我将迭代器添加到函数定义以及调用函数的位置时,都会出现错误,提示Compile Error: ByRef argument type mismatch

这是相关的代码。我删除了几行,但是您明白了要点:

Function copy_from_datatable(tool_sel As String, _
                             date_total As Integer, _
                             tool_num As Integer _
                             )
    MsgBox "In function, tool_num = " & tool_num


End Function

Sub Program()

    For tool_num = 1 To total_sites

        If tool_sel = "Badging" Then
            MsgBox "vartype " & VarType(tool_num)
            Call copy_from_datatable(tool_sel, _
                                             date_total, _
                                             tool_num _
                                             )
        End If
    Next tool_num 
End Sub

在函数调用,函数定义或循环中使用tool_num的方式是否有问题?如果我从所有内容中删除tool_num,此脚本将正常运行

1 个答案:

答案 0 :(得分:4)

只需在Sub Program()中声明变量,它就会起作用:

Function copy_from_datatable(tool_sel As String, _
                             date_total As Integer, _
                             tool_num As Integer _
                             )
    MsgBox "In function, tool_num = " & tool_num
End Function


Sub Program()
    Dim tool_sel As String
    Dim date_total As Integer
    Dim tool_num As Integer

    For tool_num = 1 To total_sites

        If tool_sel = "Badging" Then
            MsgBox "vartype " & VarType(tool_num)
            Call copy_from_datatable(tool_sel, _
                                             date_total, _
                                             tool_num _
                                             )
        End If
    Next tool_num
End Sub

我建议您在每个Option Explicit中使用Module,以避免此类错误。

希望这会有所帮助。