简体   繁体   中英

Data Validation List in excel VBA

I am trying to add values to the cell in a list format if certain criteria is met. I initially was unable to assign the values directly so i created an Array to old the values that meet the criteria. however now when i try to assign the values of the array to a cell in a list format with the below code i get a

type mismatch error

ThisWorkbook.Sheets("Plan").Cells(i, 5).Validation.Add _
      Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
      Formula1:=Join(St, ",")

Can anyone suggest how to achieve this or if there is a way to assign the values directly without holding them in an array. remember the list is not continuous an it only needs to select the values that meet my condition.

Sub try() 
Dim j,k As Long 
Dim c As Range 
Dim st As Object 
Set st=CreateObject("System.Collections.ArrayList") 
For j=5 To 150 
If(Workbook.Sheets("Plan").Cells(i,1)= Workbook.Sheets("Master").Cells(j,1))Then 
    For k= 6 To 150 
        If(Workbook.Sheets("Master").Cells(j,k)<>"") Then
            For Each c In Workbook.Sheets("Master").Cells(1,k)
                Select Case c.Value 
                    Case"Starch" st.Add Workbook.Sheets("Master").Cells(3,k)
                EndSelect 
            Nextc 
        EndIf 
    Next k 
EndIf 
Next j 

Workbook.Sheets("Plan").Cells(i,5).Validation.Add Type:=xlValidateList, _
              AlertStyle:=xlValidAlertStop, Formula1:=Join(st,",") 

End Sub

You need to get your ArrayList into a regular array before you can pass it to Join .

Eg:

Sub Tester()

    Dim st As Object

    Set st = CreateObject("System.Collections.ArrayList")
    st.Add "A"
    st.Add "B"
    st.Add "C"

    'Debug.Print Join(st, ",")         'fails with "Type Mismatch"
    Debug.Print Join(st.toarray, ",") 'Works >> A,B,C

    ActiveSheet.Cells(1, 1).Validation.Add Type:=xlValidateList, _
        AlertStyle:=xlValidAlertStop, Formula1:=Join(st.toarray, ",")

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM