Forum Discussion
Eqqsalad
Jul 24, 2023Copper Contributor
Default Value in Data Validation built off a table and allowing for multiple uses using VBA
Hello,
Another part of a prior project I'm working on:
There are two cells with two different data validation lists. List A is the primary, list B has several different lists depending on the value of list A. I would like for list B to change to a default value for each of its sub-lists. I have a semi-functional code that has worked a few times but it ends to break down on me, and I'm not sure why.
List B uses an XLookup formula in the data validation field to decide which list is available. My method for getting a default value for this list is by using VBA to change the value of the data validation cell to an xlookup formula that only uses one column of the B sub-lists as the output, making them the "default". This is set up in a way so that ideally it only changes to the default when List A changes value. For other reasons this worksheet also needs to function with automatic calculations. This sheet will also need to be able to update as List A changes value, automatically reselecting the default list B value for each List A value.
Here's the VBA code and an example of an application of the method - not the actual worksheet that needs to work. Just a VBA playground sheet.
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
With ActiveSheet
If Not Intersect(Target, Range("F3")) Is Nothing Then
'Action code
.Range("G3").Formula2 = "=XLOOKUP(F3,testTable[Alphabet],testTable[Item Default])"
End If
End With
Application.EnableEvents = True
End Sub
2 Replies
Sort By
- MarkB-MCT-alumCopper Contributor
EqqsaladSaid
I have a semi-functional code that has worked a few times but it ends to break down on me, and I'm not sure why.
Can you describe what you mean "it breaks down"?
{ ie. What does it do that you don't expect it to?} - mtarlerSilver Contributorso how does it 'break down' on you? is the problem that sometimes the set 2 value changes to default when the value in set 1 didn't change? because I could see that code getting triggered even if the value didn't change but because the drop down was activated and then the same value was re-entered (possibly even by default actions) might trigger that code. you might need to add a secondary condition like remember the prior value either using global variable or another cell on the sheet (which is essentially a global), or maybe you can check if the value already in drop down 2 is a valid option and not change if it is a valid option regardless if drop down 1 changed or not (i.e. if 'banana' is an option for set B and set C and you change drop down 1 from set B to set C then leave banana there even if it isn't in the 'normal' default column)