是否可以在VBA创建的用户定义或定制函数中使用excel内置函数?

时间:2017-04-07 19:12:25

标签: excel-vba vba excel

我正在尝试通过VBA在excel中创建一个函数,并想知道是否可以在该函数中使用excel内置函数。例如,像Lookup或Match.I这样的函数有VBA和&的解决方案。公式,但有兴趣知道函数是否可以做同样的事情。

我正在尝试创建一个函数,其中VLookup应该只为第一个找到的项返回值。

'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

1 个答案:

答案 0 :(得分:1)

以下是使用 MAX() 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

请注意,并非所有内置工作表函数都可以在VBA中使用。以下是可用的:

List of Worksheet Functions Available to Visual Basic