Reputation: 73
I am trying to create data validation cells purely with VBA. The problem is, if one of the items in the validated list is a Excel formula which contains commas (such as the IF() in the following code) an error is generated.
Dim str As String
str = "=IF(SUM(A1:A2) = 0, ""Zero"", SUM(A1:A2)) , Item 2 , Item 3 , Item 4"
s1.Range("B6").Validation.Add Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=str
The error (runtime error 1004) is generated because it delimits the string at the first comma, so the first item of the validation is "=IF(SUM(A1:A2) = 0"
. I'm hoping there are escape characters for the commas (such as \ in C) to avoid this.
I want the validated list to appear as such:
<result of IF() function>
Item 2
Item 3
Item 4
Note: I CANNOT use a range for the validated data. If the user deleted the range the spreadsheet would be broken.
Upvotes: 2
Views: 5957
Reputation: 27478
How about a WorkSheet_Change event to reset the data validation when cells A1 or A2 change?
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ValidationString As String
Dim rngChanging As Excel.Range
Dim rngWithValidation As Excel.Range
Set rngChanging = Range("A1:A2")
Set rngWithValidation = Range("B6")
If Not Intersect(Target, rngChanging) Is Nothing Then
With rngWithValidation
.Validation.Delete
If WorksheetFunction.Sum(rngChanging) = 0 Then
ValidationString = "0"
Else
ValidationString = WorksheetFunction.Sum(rngChanging)
End If
ValidationString = ValidationString & ",Item2,Item3,Item4"
.Validation.Add Type:=xlValidateList, Formula1:=ValidationString
End With
End If
End Sub
Upvotes: 1