Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to make an array to hold values for a validation list

Unable to use an array variable for data validation (Drop down list).

Also:

  1. The immediate window doesn’t show the value for MyArray when the line for debug.print is being executed.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  2. Nothing happens when the line Range("A" & r).value = MyArray(r) is executed. The excel sheet is still blank.

    Sub Testing()
    
        Dim ws As Worksheet
        Dim MyArray() As String
        Dim r As Integer
        Dim WsCount As Integer
    
        r = 1
    
        WsCount = ThisWorkbook.Worksheets.Count
        ReDim MyArray(1 To WsCount)
    
        For Each ws In ThisWorkbook.Worksheets
            MyArray(r) = ws.Name
            r = r + 1
            If r <= 12 Then
                Debug.Print MyArray(r)
                Range("A" & r).Value = MyArray(r)
            End If
        Next ws
    
        ActiveSheet.Cells(1, 2).Validation.Add _
        Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
              Operator:=xlBetween, Formula1:=MyArray
    
    End Sub
    

>Solution :

Answering your 2nd question first:
Actually, the code does execute, however what you are doing is:

  1. Fill cell at index r.
  2. Increase index r (which now points to an empty cell of your array)
  3. Write the empty string to your range

Now about the validation. Formula1 expects comma-delimited values (see here) aka a string, not an array.

You can easily correct that line of code this way (I removed the Operator which I think is unneeded).

ActiveSheet.Cells(1, 2).Validation.Add _
 Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
          Formula1:=WorksheetFunction.TextJoin(",", True, MyArray)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading