获取逗号分隔名称列表到数据验证下拉框中?

时间:2014-09-12 12:47:25

标签: vba

我在VBA中有一个名单列表:

Dim names as Variant
vNames = GetNames with some function
'vNames(1) = "Joe"
'vNames(2) = "Sarah"
'vNames(3) = "Lisa"
'vNames(4) = "Erik"

我想在许多单元格的数据下拉字段中使用它们作为替代。

如何将变量数组放入数据下拉字段?

1 个答案:

答案 0 :(得分:0)

我建议你的变种数组是一个字符串数组并使用以下内容:

Sub CreateValidation()

Dim sNames()    As String
Dim allNames    As String

'sNames = GetNames with some function
sNames = Split("Joe,Sarah,Lisa,Erik", ",") 'Used as an example

allNames = Join(sNames, ",")

With Sheets("Sheet1").Range("A1:D10").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=allNames
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = ""
    .InputMessage = ""
    .ErrorMessage = ""
    .ShowInput = True
    .ShowError = True
End With

End Sub

备注

  1. 替换" Sheet1"用你的工作表名称。
  2. 替换" A1:D10"您的范围需要验证。