简体   繁体   中英

Adding Data Validation to an excel spreadsheet using vb.net

I am trying to add Data Validation to a spreadsheet using VB.NET with data that is on Sheet2. I am able to open the workbook with both sheets and the data I need on Sheet2, but the problem I am having is populating the Data Validation Dropdown on Sheet1. I am trying to create the Data Validation in Column A and the first 700 rows of Sheet1, and the data on Sheet2 will be in Column A with the first 800 rows.

I have tried the following and it creates the Data Validation, and it only has one value inside - "Sheet2" -since I am not actually putting a formula in here.

With xlsSheet 'worksheet
    .Range(String.Concat("Sheet1!$A$2:$A$700")).Validation.Add(XlDVType.xlValidateList, & _
     Formula1:="Sheet2")
End With

When I try the following, it creates the excel sheet with the columns and the data on sheet2, but it doesn't create the data validation.

With xlsSheet 'worksheet
    .Range(String.Concat("Sheet1!$A$2:$A$700")).Validation.Add(XlDVType.xlValidateList, & _
     Formula1:="=Sheet2!$A$2:$A$800")
End With

I was looking for examples online and found http://www.get-digital-help.com/2011/10/05/add-values-to-a-data-validation-list-vba/ but this too did not work for me.

How can I get the data from A2:A800 in sheet2 into data validation on sheet1 from A2:A700?

Any help would be appreciated.

If anyone would like to know a solution to this, here is what I did:

I first created a named set that I will use to reference in the datavalidation dropdown.

workbooks.Names.Add(Name:="Working", RefersToR1C1:="=Work2!R2C1:R700" & "C1")
'Named set needed for data validation.

With xlsSheet
     .Range("Work1!$A$2:$A$700").Validation.Add(XlDVType.xlValidateList, Formula1:="=Working")
End With

In the code above you can see Work1 is the name of the sheet I want to insert the Data Validation Dropdown in. The named range is getting the data from Work2 - my second sheet.

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