0

I am trying to create a function in excel via VBA and wondering if excel inbuilt function can be used within that function. for example, functions like Lookup or Match.I have the solution with VBA & formula but interested to know if function can do the same.

I am trying to create a function where VLookup should only return value for first found item.

'function which can return the Vlookup value only for 1st found value
Function SLOOKUP(Pvalue As Range, Rng As Range, Rng1 As Range, pIndex As Long)

    Dim Cvalue As Variant
    Dim Mvalue As Long
    Dim Uvalue As Long
    Dim Result As Variant
    Result = ""

Cvalue = Pvalue.Value
Mvalue = Application.Worksheet.Function.Match(Cvalue, Rng, -1)
Uvalue = Pvalue.Row

If Mvalue = Uvalue Then
Result = Application.Worksheet.Function.VLookup(Cvalue, Rng1, pIndex, 0)
Else
Result = 0
End If

SLOOKUP = Result

End Function
6
  • 1
    The answer is "yes", with some caveats/limitations (i.e., notably UDFs are not generally allowed to alter the environment). If you'd like more specificity, you should probably include what you're trying to do, and what code you have attempted to write or use. Commented Apr 7, 2017 at 19:17
  • I have added the code. Let me know your thoughts here? Commented Apr 7, 2017 at 19:41
  • what seems to be the problem? is there an error? Commented Apr 7, 2017 at 20:17
  • yes, it doesn't return any value. when I am testing it through temporary sub, the error point is the Application.Match function where run time error 438 "Object doesn't support this property or method Commented Apr 7, 2017 at 20:23
  • 1
    Now the code works, code is correct. Worksheet.Function is wrong. it must be worksheetfunction. Commented Apr 7, 2017 at 20:27

1 Answer 1

1

Here is an example that uses MAX() and SUM():

Public Function whatever(rin As Range) As Variant
    Dim mx As Variant
    mx = Application.WorksheetFunction.Max(rin)
    whatever = Application.WorksheetFunction.Sum(rin) / mx
End Function

Note that not all built-in worksheet functions can be used like this in VBA. Here are the available ones:

List of Worksheet Functions Available to Visual Basic

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, how can I get the details which function cannot be used?
thanks for sharing the link. somehow my code doesn't work if I use Match and Vlookup.
@user3200076 worksheetfunction should have no dot in it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.