简体   繁体   中英

Multi-select list box in an excel spreadsheet using data validation

I want to achieve a multi-select list box in an excel spreadsheet using data validation.

I found a link here which talks about developer tab in MS-excel where I can drag and drop a list box control to achieve the list box effect. Possibly that is the Visual Studio tools for Office (VSTO) route. I do not want to go this route.

Instead, I'm trying to achieve it through data validation and ClosedXML nuget package.

I already have below code with the help of which I can create a drop down but not sure how can I convert it into a multi-select list box:

//imported namespaces
using ClosedXML.Excel;
using System;
using System.Data;

//code in main method
var workbook = new XLWorkbook();

DataTable userData = new DataTable("Sheet1");
userData.Columns.Add("Master Column");


workbook.AddWorksheet(userData);
var worksheet = workbook.Worksheet(1);


 DataTable validationTable = new DataTable();
 validationTable.Columns.Add("DropDownItems");
 validationTable.TableName = "Sheet2";

 DataRow dr = validationTable.NewRow();
 dr["DropDownItems"] = "Item1";
 validationTable.Rows.Add(dr);

 dr = validationTable.NewRow();
 dr["DropDownItems"] = "Item2";
 validationTable.Rows.Add(dr);

 dr = validationTable.NewRow();
 dr["DropDownItems"] = "Item3";
 validationTable.Rows.Add(dr);


 workbook.AddWorksheet(validationTable);
 var worksheet2 = workbook.Worksheet(2);
 worksheet.Column(1).SetDataValidation().List(worksheet2.Range("A2:A4"), true);

  //keep the data validation worksheet hidden
  worksheet2.Hide();

  workbook.SaveAs(@"C:\myworkbook.xlsx");

Currently this source code results in a combo box like this:

在此处输入图片说明

I've to achieve multi-select behavior programatically using ClosedXML in C#.

The Developer Tab doesn't require Visual Studio; it's just hidden away.

  • Go FileOptions → on the left: Customize Ribbon .
  • Click on the Developer checkbox under the list of Main Tabs on the right.
  • Click OK .

开发人员选项

A new 'menu' will appear on the ribbon called Developer , with categories like Code, Add-Ins, Controls, XML, Modify (varying depending on your version).

In Excel, you can't readily "convert" controls from one type to another like in Access etc, but with the Developers menu visible, you can now create a Listbox, and copy the VBA over from your Combo Box.

开发人员工具栏2

If you give the Listbox the same name the Combo Box had (after you delete the Combo Box) then the transition will be even easier. (If not there's always Ctrl + H Search & Replace!)

表单控件不受ClosedXML支持。

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