Search code examples
pythonexcelopenpyxlxlsxwriter

How can I add multiple non-consecutive cells to Name Manager in Excel using Python?


I am trying to add multiple cells, which are not always consecutive, in only one Name in Excel Name Manager using Python. You can see an example of what I want to do in the attached screenshot.

example

I have tried the Python libraries openpyxl and XlsxWriter, but both libraries can only define a specific cell or a specific range.

Examples

  • openpyxl
specific_cell = DefinedName('specific_cell', attr_text='Sheet1!$C$8')
specific_range = DefinedName('specific_range', attr_text='Sheet1!$C$8:$J$13')
  • XlsxWriter
workbook.define_name('specific_cell', '=Sheet1!$G$1')
workbook.define_name('specific_range', '=Sheet1!$G$1:$H$10')

Is there any way to add to Name Manager something more complicated than the above?

Based on the attached screenshot something like

workbook.define_name('complex_range','=Sheet1!$B$3:$E$8;Sheet1!$B$12:$C$16;Sheet1!$B$19;Sheet1!$H$12:$I$16')

Solution

  • These will work for each module, the common factor being comma rather than semi-colon?

    Xlsxwriter:

    workbook.define_name("test", "=Sheet1!$B$3:$E$8,Sheet1!$B$12:$C$16,Sheet1!$H$12:$I$16,Sheet1!$B$19") 
    

    Xlwings:

    workbook.names.add(name="test", refers_to="=Sheet1!$B$3:$E$8,Sheet1!$B$12:$C$16,Sheet1!$H$12:$I$16,Sheet1!$B$19") 
    

    Openpyxl:

    workbook.defined_names.add(DefinedName("test", attr_text="Sheet1!$B$3:$E$8,Sheet1!$B$12:$C$16,Sheet1!$H$12:$I$16,Sheet1!$B$19"))