[英]Adding String in an Array with a For Each loop
我試圖借助數組在Excel中創建下拉列表。 不幸的是,我的代碼有一些問題(我不會顯示我所有的代碼,我怕它太長了)。
這是用於在Array中添加所需內容的代碼部分:
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
以及用於創建下拉列表的代碼:
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
無論我在同一行嘗試執行什么操作,我總是會遇到相同的錯誤:
.Add Type:=xlValidateList, Formula1:=Join(Array_List, ",")
這是消息:
'1004':應用程序定義或對象定義的錯誤
我在互聯網上做過一些研究,但找不到像我這樣的問題。 經過數小時的思考,我被困住了,看不到出了什么問題,即使那肯定只是我代碼中的一個小錯誤。
有人可以告訴我您是否可以理解問題所在,我真的會很感激。
這是因為在Range("ListeD_Protection")
中必須已經有一個驗證下拉列表
所以在添加新驗證之前添加.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
我將使用定義的名稱來定義一個動態范圍,該范圍將自動更新。
這是沒有代碼的情況:
公式: =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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.