Excel VBA集合到验证列表

时间:2016-07-31 17:16:38

标签: excel vba excel-vba

我是VBA的新手,但我对Java和Python有着不错的经验。我被赋予了在excel电子表格上组织附近学校评分标准的任务,我想让教师选择通过点击按钮重新组织电子表格,所以我决定使用VBA。 / p>

这是我到目前为止我的代码(它很邋,,但是一旦我运行良好,我会清理它):

Private Sub Workbook_Open()

' Initialize Variables
Dim i%, j%
Dim vTemp$, StdList$
Dim Stds As Collection


Set Stds = New Collection

' Compute the index of the last Standard on Test worksheet
lastStd = Sheet3.Range("B" & Rows.Count).End(xlUp).Row

' Remove Duplicates from the Standards and remove commas
On Error Resume Next
For i = 2 To lastStd
    Stds.Add (Sheet3.Cells(i, 2)), Chr(34) & (Sheet3.Cells(i, 2)) & Chr(34)
Next i
On Error GoTo 0

For i = 1 To Stds.Count
    Stds.Item(i) = Replace(Stds.Item(i), ",", Chr(130))
Next i


' Sort the Standards Alphabetically (using Bubble Sort)
For i = 1 To Stds.Count - 1
    For j = i + 1 To Stds.Count
        If Stds(i) > Stds(j) Then
            vTemp = Stds(j)
            Stds.Remove (j)
            Stds.Add vTemp, vTemp, i
        End If
    Next j
Next i


' Reinitialize Cell Data
Sheet8.Range("A1:J100").Clear

For i = 1 To Stds.Count
    Sheet8.Cells(i, 1).Value = Stds.Item(i)
Next i


' Output the Standards to the Excel Spreadsheet
For i = 1 To Stds.Count
    StdList = StdList & Stds.Item(i) & ","
Next i
With ThisWorkbook.Sheets("Sheet1").Range("F3").Validation
    .Delete
    .Add Type:=xlValidateList, _
    AlertStyle:=xlValidateAlertStop, _
    Formula1:=StdList
End With
End Sub

当我打开电子表格时执行代码,但是我得到了"运行时错误1004'应用程序定义或对象定义错误'"执行时目标是让代码通过评分标准进行搜索,枚举集合,删除重复项,按字母顺序对标准进行排序,并使用看起来像逗号的字符替换逗号,以便我可以将集合转换为列表和位置列表到电子表格某处的下拉列表中。当我选择调试选项时,这三行会突出显示:

    .Add Type:=xlValidateList, _
    AlertStyle:=xlValidateAlertStop, _
    Formula1:=StdList

我的猜测是,我要么在语法上挣扎,要么在那里我看不到某种类型的不匹配;两者都可能。

1 个答案:

答案 0 :(得分:4)

您可以在参数上运行debug.print - 这会指出xlValidateAlertStop为空

实际应该是xlValidAlertStop