Excel宏中的数据验证功能中出现#VALUE错误

时间:2015-03-30 19:39:14

标签: vba function

我有这个功能。但我有#VALUE错误。怎么解决这个问题?

Function UYGULAMAADI(ByVal Target As Excel.Range)

Sheets("Sheet1").Range(Target).Select
With Selection.Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, _
Formula1:="=IF(OFFSET(" & Target & ";0;1;1;1)='stackoverflow';INDIRECT('x1');INDIRECT('x2'))"
.IgnoreBlank = True
.InCellDropdown = True
End With

End Function  

1 个答案:

答案 0 :(得分:0)

从工作表中调用的函数(即,当您将其放入单元格中以调用函数时,= UYGULAMAADI(A1))无法对此类工作表对象进行操作。几乎所有范围和工作表方法都禁止在这种方式调用的UDF中,以防止循环引用错误,依赖性错误,无限循环等。

您正在使用Target作为输入 - 也就是说,您希望将验证添加到目标单元格。您可以在子例程

中使用Selection执行相同的操作
Sub UYGULAMAADI()

'Applies this macro to the range currently SELECTED by the user

With Selection.Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, _
Formula1:="=IF(OFFSET(" & Selection.Value & ";0;1;1;1)='stackoverflow';INDIRECT('x1');INDIRECT('x2'))"
.IgnoreBlank = True
.InCellDropdown = True
End With

End Sub

或者,提示用户输入:

Sub UYGULAMAADI()

'Prompts the user for an input/range
Dim rng as Range
Set rng = Application.InputBox("Select a cell", Type:=8)

If rng Is Nothing Then Exit Sub

With rng.Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, _
Formula1:="=IF(OFFSET(" & Selection.Value & ";0;1;1;1)='stackoverflow';INDIRECT('x1');INDIRECT('x2'))"
.IgnoreBlank = True
.InCellDropdown = True
End With

End Sub