Excel VBA收集到validation列表

我对VBA相当陌生,但是我对Java和Python有相当丰富的经验。 我被赋予了在Excel电子表格上组织附近学校的评分标准的任务,并且我想让教师按下button来重新组织电子表格,所以我决定使用VBA。

这是我到目前为止对我的代码(这是马虎,但我会清理它,一旦我得到它的工作):

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”应用程序定义错误或“对象定义错误”。 目标是让代码通过分级标准进行search,枚举集合,删除重复项,按照字母顺序sorting标准,并将逗号replace为看起来像逗号的字符,以便将集合转换为列表和地方将其列入电子表格的某个下拉列表中。 当我selectdebugging选项时,这三行将突出显示:

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

我的猜测是,我要么在语法上挣扎,要么在那里有一个types不匹配,我没有看到; 这两者都是可能的。

你可以在你的参数上运行debug.print – 这会指出xlValidateAlertStop是空的

它实际上应该是xlValidAlertStop