问题
Normally it is possible to apply data validation in excel through vba but i am having a specific problem
I am using the indirect method for applying validation,normally when i dont use vba i get a warning by excel that "source currently evaluates to an error,do u want to continue?" (this is because cells which indirect refers to may be empty), now i can easily skip this error in excel by clicking "Yes"
Here's the link http://www.contextures.com/xldataval02.html (Dependent validation lists)
But when i try to perform the same thing using vba i am getting a runtime error,there is no friendly prompt which allows me to continue.How can i handle this kind of error.
On error resume isnt working because then vba doesnt apply validation at all.
Here's the code
Set rng = ThisWorkbook.Sheets("input").Range("AB11:AB65536")
With rng.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:= _
"=INDIRECT(cablecode&""_depth_""&$Q11&""_""&$Z11&""_values"")"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
cablecode is a static named range
Q11 and Z11 refer to inputs in that particular row
depth and values are normal strings
cablecode can have two values = "is" or "iec"
Q11 can be "xlpe" or "pvc"
Z11 can be "al" or "cu"
since cablecode is constant for whole project ive referred to it directly, Q11 and Z11 can be different for different rows so ive referred to them seperately
The whole string comes out to be "is_depth_al_xlpe_values" similarly different permuations,and all named ranges are already defined
回答1:
I suppose the following line needs correction from
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:= _
"=INDIRECT(cablecode&""_depth_""&$Q11&""_""&$Z11&""_values"")"
to
dim cellToBeReferred as string
cellToBeReferred = cablecode & "_depth_" & Range("$Q11").Value & "_" _
& Range("$Q11").Value & "_values"
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:= _
"=INDIRECT(" & cellToBeReferred & ")"
Taking the string out will help you debug the issue and figure what is the value of named range, you'd want to refer to. See what value cellToBeReferred
results into and correct the concatenation using above.
EDIT after reading OPs comment
In that case, surround the INDIRECT
with ISERROR
and give a dummy cell reference.
For e.g.
"=IFERROR(INDIRECT(" & cellToBeReferred & "), Z1)"
Where Z1 is a cell to be referred if INDIRECT
fails.
来源:https://stackoverflow.com/questions/10510160/data-validation-with-vba