2015-03-30 120 views
0

我有这个功能。但我有#VALUE错误。如何解决此问题?#宏Excel数据验证功能错误

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

从工作表中调用(即'= UYGULAMAADI(A1)'当你的函数把它放在一个单元格中调用函数)不能在这样的工作表对象上操作。具体来说,'.Select'方法可能是导致函数提前中止的原因。我期望'.Validation'方法也会出错。 – 2015-03-30 19:42:03

+0

谢谢@David。你对解决方案有什么建议? – 2015-03-30 19:48:07

+0

这取决于问题。你想做什么?我解释了为什么这不起作用。只要你提供一种方法来传递一个范围参数(inputbox,或者使用'Selection'作为输入等等),它应该很可能作为一个sub来使用。 – 2015-03-30 20:01:57

回答

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