VBA使用数组值作为单元格验证值

时间:2015-07-09 01:33:14

标签: excel vba excel-vba

我现在在做什么,

  1. 使用来自多个工作表的特定列(项目列)使用唯一数据填充数组
  2. 使用上面的数组值
  3. 填充不同工作表中的下拉列表

    但是,我在验证步骤中出错,我尝试设置Formula1:=arrItems()

    这是我的代码:

        Dim ws As Worksheet
        Dim tmpItems As String
        Dim arrItems() As String
        Dim tmpDates As String
        Dim arrDates() As String
        Dim ItemColumn As Range
        Const ItemHeaderCell As String = "Item"
        Dim EmptyRange As Range
    
        For Each ws In ActiveWorkbook.Worksheets
          If ws.Name <> "Raw Data" Then
            ws.ListObjects.Add(xlSrcRange, ws.UsedRange, , xlYes).Name = ws.Name
            ws.ListObjects(ws.Name).TableStyle = "TableStyleMedium9"
            tmpDates = tmpDates & ws.Name & "|"
            Set ItemColumn = ws.UsedRange.Find(ItemHeaderCell, , xlValues, xlWhole)
    
            For Each EmptyRange In Intersect(ItemColumn.EntireColumn, ws.UsedRange).Cells
            'skip the header and empty cells
              If Not IsEmpty(EmptyRange.Value) And EmptyRange.Address <> ItemColumn.Address 
            And (InStr(tmpItems, EmptyRange) = 0) Then
                tmpItems = tmpItems & EmptyRange.Value & "|"
              End If
            Next EmptyRange
          End If
        Next ws
    
        If Len(tmpItems) > 0 Then 
           tmpItems = Left(tmpItems, Len(tmpItems) - 1)
           arrItems = Split(tmpItems, "|")
    
           If Len(tmpDates) > 0 Then 
             tmpDates = Left(tmpDates, Len(tmpDates) - 1)
             arrDates = Split(tmpDates, "|")
    
             Dim worksheet2 As Worksheet
             Set worksheet2 = ActiveWorkbook.Sheets.Add(Before:=ActiveWorkbook.Sheets(1))
             worksheet2.Name = "Main"
    
             With worksheet2.Range("A1").Validation
                .Delete
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=arrItems()
             End With
    

    如何纠正此错误?

1 个答案:

答案 0 :(得分:1)

Validation.Formula1是一个字符串,而不是一个数组。如果我正确地阅读您的代码,您可以将填充tmpItems的行更改为:

tmpItems = tmpItems & EmptyRange.Value & ","

之后,只需删除最后一个逗号并使用tmpItems作为Formula1