如何向动态验证列表(VBA)中添加其他选项?

时间:2018-08-16 12:03:40

标签: excel-vba validation

我有一个表,其中的ID分为不同的组(一组可以包含2个以上的元素)。

对于“ E”列,您只能从每一行的相关组中选择一个ID。示例:

enter image description here

代码:

Sub data_validation()
Dim colNum      As Long
Dim i           As Long
Dim k           As Long

colNum = Range("A1", Range("A1").End(xlToRight)).Cells.Count
i = 2
Do Until Cells(i, 1) = ""
    k = 0
    Do While Cells(i, 1).Value = Cells(i + 1, 1).Value
       k = k + 1
       i = i + 1
    Loop

    With Range(Cells(i - k, colNum + 2), Cells(i, colNum + 2)).validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
    Operator:=xlBetween, Formula1:="=$B$" & i - k & ":$B$" & i
    End With

    i = i + 1
Loop
End Sub

如何将-(连字符)符号添加到与VBA一起使用的选择列表中?我尝试了并集范围,但是导致类型不匹配。

1 个答案:

答案 0 :(得分:1)

您似乎没有一个用于数据验证的列表,该列表是范围的并集(当我尝试不通过VBA在Excel中执行此操作时,错误消息为You may not use reference operators (such as unions, intersections, and ranges) or array constants for Data Validation criteria.),因此在我看来,最好的选择是使列表为手动列表,而不是引用范围。您可以使用以下代码创建这样的列表:

Sub data_validation()
Dim colNum      As Long
Dim i           As Long
Dim k           As Long
Dim ValidationListFormula As String

colNum = Range("A1", Range("A1").End(xlToRight)).Cells.Count
i = 2
Do Until Cells(i, 1) = ""
    k = 0
    ValidationListFormula = Cells(i, 2).Value
    Do While Cells(i, 1).Value = Cells(i + 1, 1).Value
       k = k + 1
       i = i + 1
       ValidationListFormula = ValidationListFormula & "," & Cells(i, 2).Value
    Loop

    ValidationListFormula = ValidationListFormula & ",-"
    With Range(Cells(i - k, colNum + 2), Cells(i, colNum + 2)).Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
            Operator:=xlBetween, Formula1:=ValidationListFormula
    End With

    i = i + 1
Loop
End Sub