A value used in the formula is of wrong data type when calling a UDF

为君一笑 提交于 2019-12-11 02:37:04

问题


I've been trying hard to figure out what went wrong here. I have two cols which contain string values. I use the third col to call a UDF in the worksheet, but end up getting #Value with error - "A value used in the formula is of wrong data type".

Eg:

 Col I   Col J
 File1    Y
 File1    N
 File2    Y
 File3    N

I tried debugging it, and the input values were passed fine into the function variables. My knowledge in VBA is limited, hoping you guys can help me out in resolving this issue.

Function called in worksheet:

=FileCheck(I3,I3:J38)

Code:

Public Function FileCheck(V As Range, Q As Range) As String
    Dim vtest As Variant
    Dim i, j, stat As Integer

    stat = 0

    vtest = Q

    For i = 1 To UBound(vtest)
        If V = vtest(i, 1) And vtest(i, 2) = "N" Then

            For j = 1 To UBound(vtest)
                If V = vtest(j, 1) And vtest(j, 2) = "Y" Then

                    FileCheck = "Y"
                    stat = 1
                End If
            Next
            If stat = 0 Then
                FileCheck = "N"
                End
            Else: End
            End If


        ElseIf V = vtest(i, 1) And vtest(i, 2) = "Y" Then
            FileCheck = "Y"
        End If
    Next

End Function

回答1:


You are getting that error because you are using End.

When you want to turn your computer off, do you click on Start Menu ~~> Shut down or do you pull the power cable out directly? :-)

Using End is very similar to pulling the cable. Don't use End. Exit the function gracefully. The End statement is basically a way of making your program crash, but without showing any error messages.

Try this. Replace these lines

If stat = 0 Then
    FileCheck = "N"
    End
Else: End
End If

with

If stat = 0 Then FileCheck = "N"
Exit Function

EDIT

BTW, are you trying to find the corresponding value of Col I in Col J? If yes, then you do not need a UDF for this. You can use Vlookup()

Use this formula =VLOOKUP(I3,I3:J38,2,0) instead of =FileCheck(I3,I3:J38)




回答2:


I think your first input type should be a string not a range:

V as string

Additional you need to use exit function when you want to end the function however I'm not sure if you want to end the function, end the if statement or the for loops?



来源:https://stackoverflow.com/questions/14460039/a-value-used-in-the-formula-is-of-wrong-data-type-when-calling-a-udf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!