使用For Each循环在数组中添加string

我试图创build一个下拉列表在Excel的帮助下,一个数组。 不幸的是,我的代码存在一些问题(我不会显示我所有的代码,恐怕它太长了)。

下面是添加我想要在数组中的代码的一部分:

Dim Range_Protection As Range Dim Row_Range As Range Dim Tableau As Range Dim Protection_First_Value As String Dim Protection_Last_Value As String Dim Array_List() As String Dim Taille_Array As Integer If Not Range_Protection Is Nothing Then 'The value I want to get are String, don't know if I should use "Cells.Text" instead Protection_First_Value = Tableau.Cells(1, 1).Value For Each Row_Range In Range_Protection.Rows Protection_Last_Value = Row_Range.Cells(1, 1).Value 'I'm checking the value of each rows 'Everytime there is a new value, I add it to the Array If Protection_First_Value <> Protection_Last_Value Then Protection_First_Value = Protection_Last_Value 'Taille_Array is already determined earlier in the code For Count = 0 To Taille_Array Array_List(Taille_Array) = Protection_Last_Value Next Count Else End If Next Row_Range End If 

和创build下拉列表的代码:

 With Range("ListeD_Protection").Validation .Add Type:=xlValidateList, Formula1:=Join(Array_List, ",") .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = True End With 

我总是有同样的错误,不pipe我在同一行上做什么:

  .Add Type:=xlValidateList, Formula1:=Join(Array_List, ",") 

这里是消息:

'1004':应用程序定义或对象定义的错误

我在互联网上做了一些研究,但没有发现类似于我的问题。 经过几个小时的思考,我被困住了,看不出有什么问题,即使它在我的代码中确实只是一个小小的错误。

有人能告诉我,如果你能明白什么是问题,我会非常感激。

这是因为在Range("ListeD_Protection")中必须已经有一个validation下拉列表

所以在添加新的validation之前添加.Delete

 With Range("ListeD_Protection").Validation .Delete .Add Type:=xlValidateList, Formula1:=Join(Array_List, ",") .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = True End With 

我会使用一个定义的名称来定义一个dynamic范围,它会自动更新自己。

这里是你如何做到没有代码:


公式: =OFFSET(A1,1,0,COUNTA(A:A)-1,1)

在这里输入图像说明

这是可编程的代码:


 Worksheets("Sheet1").Range("OFFSET(A1,1,0,COUNTA(A:A)-1,1)").Name = "Accepted_Colors" With Selection.Validation .Delete .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _ xlBetween, Formula1:="=Accepted_Colors" .IgnoreBlank = True .InCellDropdown = True .InputTitle = "" .ErrorTitle = "" .InputMessage = "" .ErrorMessage = "" .ShowInput = True .ShowError = True End With 

这里是你如何使用ArrayList重构你的代码:

 Dim Range_Protection As Range Dim Row_Range As Range Dim Tableau As Range Dim ValidationList As String Dim Array_List As Object Set Array_List = CreateObject("System.Collections.ArrayList") Dim Taille_Array As Integer If Not Range_Protection Is Nothing Then 'The value I want to get are String, don't know if I should use "Cells.Text" instead Protection_First_Value = Tableau.Cells(1, 1).Value For Each Row_Range In Range_Protection.Columns(1) If Not Array_List.Contains(Row_Range.Value) Then Array_List.Add Row_Range.Value Next Row_Range Array_List.Sort ValidationList = Join(Array_List.ToArray, ",") End If