Home » excel » Excel VBA dynamic data validaiton gives "Application-defined object" error

Excel VBA dynamic data validaiton gives "Application-defined object" error

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to get Data Validation drop down into cell “B22” in worksheet “Data” when the workbook is opened. I get this error

Run-time error '1004'
Application-defined object error

And the application breasks at this code:

.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=value_list

Here is the WorkbookOpen() Sub:

Private Sub Workbook_Open()
    Dim oCon As ADODB.Connection
    Dim oRS As ADODB.Recordset
    Dim rng As Range

    Set oCon = New ADODB.Connection
    oCon.ConnectionString = "Provider=SQLOLEDB;Data Source=MARS;Initial Catalog=automation;Trusted_connection=yes;"
    oCon.Open
        Set oRS = New ADODB.Recordset
        oRS.ActiveConnection = oCon
        oRS.Source = "select insurer.name from person as insurer where insurer.person_class_id = 2 order by insurer.name asc"
        oRS.CursorType = adOpenStatic
        oRS.Open
        value_list = ""

     Do While Not oRS.EOF
         value_list = value_list & oRS(0) & ","
         r = r + 1
         oRS.MoveNext
     Loop

     value_list = Mid(value_list, 1, Len(value_list) - 1)

     With Sheets("Data").Range("B22").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=value_list
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With

    oRS.Close
    oCon.Close
End Sub
How to&Answers:

I did some testing and found that (in Excel 2003 at least) if value_list is greater than 255 characters in length you will get this error.

A possible workaround might be to load the list values into a named range and assign Formula1:="=YourRangeName", but I have not tested this.