简体   繁体   中英

Update Data Validation List Range

I'm trying to create a vba code that will update my data validation list range to last row on another sheet. My dropdown list is on my "Home" tab which takes its list range from column P on "Mapping tab". The list will change daily so wanted to add in the formaula to look for finalrow rather than entering a cell row value. Here is the code I have written but a error occurs with the formula.

Sub getDropdownList()

    Dim finalrow1 As Integer

    'finds last row in Column P on Mapping tab
    Sheets("Mapping").Select
    finalrow1 = ActiveSheet.Cells(Rows.Count, "P").End(xlUp).Row

    Sheets("Home").Select
        Range("E7").Select
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=Mapping!$P$1:$P &finalrow1"

    End With

    End Sub

I have no idea if this will work but try changing the formula to

Formula1:="=Mapping!$P$1:$P" & finalrow1

excel is probably treating your integer as a string and getting confused.

No need to use VBA to update the formula - use a dynamic formula (as a named range) instead.
As a named range this will reference from $P$1 to the last cell containing data - providing there are no blank cells in the column P list.
=Mapping!$P$1:INDEX(Mapping!$P:$P,COUNTA(Mapping!$P:$P))

This needs to be entered as a named range as data validation won't accept it.

Did I mention it has to be a named range and not entered directly to the Source box? :)

On the VBA you did this line wrong:

xlBetween, Formula1:="=Mapping!$P$1:$P &finalrow1"

Please see correction below for that line in your code:

xlBetween, Formula1:="=Mapping!$P$1:$P" & finalrow1

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