Setting validation via VBA in excel fails when using variable

后端 未结 6 2049
野趣味
野趣味 2021-01-06 07:56

I am trying to set the data validation for a range of cells using VBA. I get a run-time error 1004 (so helpful) \"Application defined or object defined error\" with this cod

6条回答
  •  独厮守ぢ
    2021-01-06 08:58

    This probably should be a comment too, especially since this post is so old...I had the same problem, where it would work some of the time and not others. Using a dynamically named range. The solution that I found was to unlock the sheet temporarily.

    Private Sub FixDropdownLists()
    
    Sheet1.Unprotect Password:="afei31afa"
    Dim cellv As Range
    
    For Each cellv In Sheet1.Range("B18:E18,B32:E32")
        With cellv.Validation
            .Delete
            .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="=Office_Locations"
            .IgnoreBlank = True
            .InCellDropdown = True
            .InputTitle = ""
            .ErrorTitle = "Invalid Input"
            .InputMessage = ""
            .ErrorMessage = "Select the location only from the dropdown list."
            .ShowInput = False
            .ShowError = True
        End With
    Next cellv
    Sheet1.Protect Password:="afei31afa"
    End Sub
    

提交回复
热议问题