是否可以在两个不同范围内创建一个名称以用于列表(数据验证)?
我有两列: A ,其内容在第1至3行中; C ,其内容在第1至4行中。
我尝试使用ThisWorkbook.Names.Add Name:="TheList", RefersTo:=Range("A1:A3,C1:C4")
,但是在数据验证字段中插入=TheList
时,它显示“列表源必须是定界列表,或者是对单个行或列的引用”。
是否有一种方法可以合并两列中的值?
答案 0 :(得分:1)
由于Excel要求使用连续范围的值作为数据验证列表,因此您确实有两个选择。
对于这种方法,我将在“ Z”列(或可能在另一个隐藏的工作表)中建立一个列表出口。这是一个示例:
Option Explicit
Sub MakeValidationRange()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim dataRange As Range
Set dataRange = ws.Range("A1:A3,C1:C3")
Dim valRange As Range
Set valRange = ws.Range("Z1")
Dim entry As Variant
For Each entry In dataRange
valRange.Formula = "=" & entry.Address
Set valRange = valRange.Offset(1, 0)
Next entry
Set valRange = ws.Range("Z1").CurrentRegion
'--- alternate method using a named range
ThisWorkbook.Names.Add Name:="TheList", RefersTo:=valRange
Dim dropDownCell As Range
Set dropDownCell = ws.Range("B1")
dropDownCell.Validation.Delete
dropDownCell.Validation.Add Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:="=TheList"
'--- alternate method without creating a named range
Set dropDownCell = ws.Range("B2")
dropDownCell.Validation.Delete
dropDownCell.Validation.Add Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:="=(" & valRange.Address & ")"
End Sub
此操作的关键在于定义.Validation.Add
方法的列表不等号。例如,验证列表将为Red,Orange,Yellow,Green,Blue,Indigo,Violet
。没有双引号。没空间了。不等于这是示例:
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")
dropDownCell.Validation.Delete
dropDownCell.Validation.Add Type:=xlValidateList, _
AlertStyle:=xlValidAlertStop, _
Formula1:=dataList
End Sub