简体   繁体   中英

data validation excel vba

Option Explicit

Sub MakeValidationList()
    Dim ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Sheet1")

    Dim dataRange As Range
    Set dataRange = ws.Range("A1:A3,C1:C3")

    Dim dataList As String
    Dim entry As Variant
    For Each entry In dataRange
        dataList = dataList & entry.Value & ","
    Next entry
    '--- remove the last trailing comma
    dataList = Left$(dataList, Len(dataList) - 1)

    Dim dropDownCell As Range
    Set dropDownCell = ws.Range("B3:B10")
    dropDownCell.Validation.Delete
    dropDownCell.Validation.Add Type:=xlValidateList, _
                                AlertStyle:=xlValidAlertStop, _
                                Formula1:=dataList
End Sub

from the data above, how can the datavalidation range be taken from sheet2, because it works for sheet1 (the same sheet)? request the learning

I would say there are two easy options to pull data from an other sheet into a Validation.Add method. The below is just an example to show you the technique:

Sub Test()

'Set your two worksheets
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Worksheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Worksheets("Sheet2")

'Set your range objects where you want a validation list
Dim rng1 As Range: Set rng1 = ws1.Range("A1")
Dim rng2 As Range: Set rng2 = ws1.Range("B1")

'Set your source range
Dim rng3 As Range: Set rng3 = ws2.Range("A1:A3")

'Set an array (for option 1)
Dim arr As Variant: arr = rng3.Value

'Option 1:
rng1.Validation.Add xlValidateList, Formula1:=Join(Application.Transpose(arr), ",")

'Option 2:
rng2.Validation.Add xlValidateList, Formula1:="='" & ws2.Name & "'!" & rng3.Address

End Sub

With option 1 you can add any 2D-Array to the validation list (drop the Application.Transpose if you already got one in memory).

With option 2 you refer to another worksheet within a concatenated formula.

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