在VBA Sub中使用Function

时间:2018-01-10 11:07:51

标签: excel vba excel-vba

我正在尝试在我的Sub中运行一个函数但是在x = NINOFunction()行上遇到编译错误,我不知道如何让它工作。

Sub CheckNINO()
    Dim NINumber As Range, NINumbers As Range
    Dim Usdrws As Long, x As Boolean

    Usdrws = Worksheets("EeeDetails").Range("C" & Rows.Count).End(xlUp).Row
    Set NINumbers = Worksheets("EeeDetails").Range("Q2:Q" & Usdrws)

    For Each NINumber In NINumbers
        x = NINOFunction(NINumber.Value)
        If x = False Then
            Range(NINumber).Copy Destination:=Worksheets("Validation").Cells(2, x)
        End If
    Next
End Sub

Function NINOFunction(sInp As String) As Boolean
    Const s1 As String = "[AaBbCcEeGgHhJjKkLlMmNnOoPpRrSsTtWwXxYyZz]"
    Const s2 As String = "[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtWwXxYyZz]"
    Const s3 As String = "######"
    Const s4 As String = "[AaBbCcDd]"

    NINO = sInp Like s1 & s2 & s3 & s4
End Function

测试该函数并使用布尔结果。

如果结果为False,我想将行复制到单独的工作表中。

2 个答案:

答案 0 :(得分:2)

您的编译错误是“参数不是可选的”。这是非常好的错误消息。因此,写x = NINOFunction(arg)并放置一个参数sInp

x = NINOFunction ("something")

这样的东西

或者你可能需要:

x = NINOFunction (NINumber)

此外,您的函数始终返回False,因为这是布尔函数的默认值。您可以考虑修改它:

Function NINOFunction(sInp As String) As Boolean
    Const s1 As String = "[AaBbCcEeGgHhJjKkLlMmNnOoPpRrSsTtWwXxYyZz]"
    Const s2 As String = "[AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtWwXxYyZz]"
    Const s3 As String = "######"
    Const s4 As String = "[AaBbCcDd]"

    NINOFunction = sInp Like s1 & s2 & s3 & s4
End Function

答案 1 :(得分:0)

NINOFunction接受1个参数,这是一个字符串,但你没有通过任何参数。试试x = NINOFunction("something")