I have the following code:
Function createCascadingDropDown(sourceTable As ListObject, targetTable As ListObject, targetTableCorespondingColumn As Integer, targetWs As Worksheet, targetWsDropDownColumn As Integer)
Dim currentDropDownList As String, dropDownName As String, formula As String
Dim validationVariable As Validation
currentDropDownListName = targetWs.Name & "CurrentDropDownList"
dropDownName = targetWs.Name & "DropDown"
targetWs.Names.Add Name:=currentDropDownListName, RefersToLocal:="=INDEX(" & targetWs.Name & "!" & currentDropDownListName & ";1;1):INDEX(" & targetWs.Name & "!" & currentDropDownListName & ";COUNTA(" & targetWs.Name & "!" & currentDropDownListName & "))"
targetWs.Names.Add Name:=dropDownName, RefersToLocal:="=INDEX(" & sourceTable.Name & ";0;MATCH(INDEX(" & targetTable.Name & "[@];" & CStr(targetTableCorespondingColumn) & ");" & sourceTable.Name & "[#Headers];0))"
formula = "=" & dropDownName
With targetWs.columns(targetWsDropDownColumn).EntireColumn.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=formula
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.InputMessage = ""
.ErrorTitle = ""
.ErrorMessage = ""
.ShowInput = False
.ShowError = True
End With
targetWs.Cells(1, targetWsColumn).Validation.Delete
End Function
In general I am trying to programmatically build up a cascading drop-down-menu like in https://www.contextures.com/exceldatavaldependindextables.html.
The problem occurs in the line where I add the validation. Here the error "Application-defined or object-defined error" comes up.
When I add a break point and do this step manually it works, despite the fact, that excel tells me "The source currently evaluates to an error. Do you want to continue?". It might be that this is the problem; at least I found this and this, which both did not help. Wrapping IFERROR around the formula makes it invalid.
So I also tried to set the RefereToLocal to an empty cell (e.g. "=$A$20") and change it afterwards. Now the problem is, that it does not accept the exact same formula again:
targetWs.Names.Item(dropDownName).RefersToLocal ="=INDEX(" & targetWs.Name & "!" & currentDropDownListName & ";1;1):INDEX(" & targetWs.Name & "!" & currentDropDownListName & ";COUNTA(" & targetWs.Name & "!" & currentDropDownListName & "))"
I am really running out of ideas. In case you have any to solve also the original problem (implement a vba-free cascading drop-down using vba) I would be happy to about them!
targetWS.Names(currentDropDownListName).RefersToLocalandtargetWs.Names(dropDownName).RefersToLocalbefore the line which causes an error? Is it a valid formula? Have you tried to manually set a validation to a cell using exactly the same formula?