带有数据验证列表的循环vba

时间:2016-11-04 10:09:46

标签: vba excel-vba for-loop excel

我想通过使用循环来执行列表的数据验证,但是我在此行上抛出了错误1004:

 .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=lista" & i

这是整个代码:

Sub sampllle()
  For i = 2 To 6
  With Sheets("HSZI AD").Range("H972:H978").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=lista" & i
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
    Next i
    End Sub

3 个答案:

答案 0 :(得分:0)

让我们退后一步。您的代码似乎应用了五次验证,但您每次都要删除它,以便只保留最后一个。你有命名范围“lista2”等吗?

答案 1 :(得分:0)

试试这个

Sub sampllle()

Dim i As Long

Sheets("HSZI AD").Range("H972:H978").Validation.Delete

For i = 2 To 6
    With Sheets("HSZI AD").Range("H972").Offset(i - 2).Validation
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=lista" & i
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
Next i

End Sub

答案 2 :(得分:0)

我意识到我必须在要转换为数据验证列表的单元格中具有某些价值的问题。它现在有效