VBA自定义Excel函数与下拉列表

我有我的自定义函数在Excel(VBA)中,但我正在尝试在CELL函数中做这样的列表:

在Excel中尝试:

= CELL(info_type [然后出现下拉列表]

所以,我想:

= MyFunction(my_variable [和我的自定义下拉列表]

该列表应显示在Excel中,而不是在VBA窗口中。

有人知道怎么做这个吗?

对不起,我无法发表图片。

这是一个笨重的方法,可能工作。 这个想法是使用Worksheet_Change事件来捕获您inputfunction的不完整版本的实例,在该阶段,在单元格上显示一个即时数据validation下拉列表,为您提供完成该function的可能方法。 然后,再次使用Worksheet_Change ,检测完成的版本,转换成公式,并删除数据validation。

作为一个概念certificate – 我写了一个sin的版本,允许用户select“度”或“弧度”:

 Function Sine(ParamArray args() As Variant) As Variant On Error GoTo err_handler If args(1) = "Degrees" Then Sine = Sin(args(0) * Application.WorksheetFunction.Pi() / 180) Else Sine = Sin(args(0)) End If Exit Function err_handler: Sine = "=Sine(" & args(0) & "," End Function 

如果用户没有至less给出一个angular度,则会抛出未被捕获的错误。

然后,在Worksheet_Change我使用了:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim choices As String, angle As String, tval As String On Error GoTo err_handler tval = Target.Value If tval Like "=Sine(*," Then angle = Mid(tval, 7) angle = Left(angle, Len(angle) - 1) 'get rid of comma choices = angle & " Degrees, " & angle & " Radians" Target.Validation.Add xlValidateList, Formula1:=choices Target.Select ElseIf tval Like "* Degrees" Then Target.Validation.Delete Target.Formula = "=Sine(" & Val(tval) & ", ""Degrees"")" Target.Offset(1).Select ElseIf tval Like "* Radians" Then Target.Validation.Delete Target.Formula = "=Sine(" & Val(tval) & ", ""Radians"")" Target.Offset(1).Select End If err_handler: End Sub 

它是这样工作的。 在A1(比如说)input=Sine(45然后回车,你会看到下面的内容(点击下拉箭头后):

在这里输入图像说明

然后,在select例如“45度”之后,A1中的公式变成

 =sine(45, "Degrees") 

并显示值(0.707107),数据validation已被删除。

可能更灵活的想法的一个变体是显示单元格的用户表单,而不是依靠这个数据validation黑客。