简体   繁体   中英

VBA to programmatically put value in cell when adding data validation list

I am fully versed in VBA but not certain if this is possible or not as I couldn't find anything while searching for the past 15 minutes.

I add a data validation list in the usual manner

startCell.Offset(1, 2).Select
With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=Categories"
    .IgnoreBlank = True
    .InCellDropdown = True        
End With

But when the routine finishes none of the values are selected and therefore the cell is blank.

Is there a way to set the cell value when adding the data validation, ie a default value maybe the first item in the data validation list?

Try this:

With startCell.Offset(1, 2)
    With .Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
             Operator:= xlBetween, Formula1:="=Categories"
        .IgnoreBlank = True
        .InCellDropdown = True
    End With
    .Value = Range("Categories").Cells(1).Value
End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM