2017-04-07 79 views
0

我想通过VBA在excel中创建一个函数,并想知道是否可以在该函数内使用excel内置函数。例如,查找或匹配等功能。我有与VBA &公式的解决方案,但有兴趣知道功能是否可以做到这一点。是否可以在由VBA创建的用户定义或定制函数中使用excel内置函数?

我想创建一个函数,其中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

的答案是“是”,有一些注意事项/限制(即,特别是UDF是不一般不允许改变环境)。 如果你想要更多的特殊性,你应该包括你想要做什么,以及你试图编写或使用什么代码。 –

+0

我已添加代码。让我知道你的想法吗? – user3200076

+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

+0

谢谢,我怎样才能获得哪些功能无法使用的细节? – user3200076

+0

@ user3200076看我的编辑 –

+0

感谢分享如果我使用Match和Vlookup,我的代码不起作用 – user3200076

相关问题