5

I am trying to add drop down in excel cell using python win32com api. But not able to implement it.

Here is my code

from win32com.client import Dispatch
import os
import win32api
path = os.getcwd()

path1 = path + '\\myExcel.xlsx'
try:
    xl = Dispatch("Excel.Application")   
    xl.Visible = 1  # fun to watch!
    wb = xl.Workbooks.Open(Filename=path1)

    ws = wb.Worksheets(1)

    ws.Cells(1,1).Value = "GREEN"
    ws.Cells(2,1).Value = "YELLOW"
    ws.Cells(3,1).Value = "RED"
    ws.Cells(4,1).Value = "WHITE"
    ws.Cells(5,1).Value = "NOT SURE"
    ws.Cells(6,1).Value = "["GREEN", "YELLOW", "RED", "WHITE", "NOT SURE"]" //I want drop down here
    wb.Close(SaveChanges=True)
    xl.Quit()
except Exception as e:
    print(e)
Saurabh Agrawal
  • 7,581
  • 2
  • 27
  • 51
  • What is a dropdown list? Is it a filter? – ycx Jan 07 '19 at 09:40
  • @ycx it's a list. Edited my question. :) – Saurabh Agrawal Jan 07 '19 at 09:56
  • Where is your question? –  Jan 07 '19 at 10:01
  • @MediaEU how to add drop down list in excel cell using win32com python?? `ws.Cells(6,1).Value = "["GREEN", "YELLOW", "RED", "WHITE", "NOT SURE"]" //I want drop down here` – Saurabh Agrawal Jan 07 '19 at 10:14
  • What we would like to know is the official name of the Excel construct that you wish to create in your Python code – David Heffernan Jan 07 '19 at 11:05
  • 1
    What OP wants to do is what you can do interactively in Excel 2016 this way: Data tab | Data Tools pane | Data Validation | Data Validation... | Settings | Allow: List, Source: . Here is a way to do it in VBA: https://software-solutions-online.com/excel-vba-drop-down-lists/#Jump2 – BoarGules Jan 07 '19 at 11:16
  • @DavidHeffernan yes it does.. You can check the link `BoarGules` has posted. It is doing the same thing but using VBA – Saurabh Agrawal Jan 07 '19 at 11:31
  • @BoarGules thanks for the solution but I want to do it using `win32com` – Saurabh Agrawal Jan 07 '19 at 11:32
  • 1
    @SaurabhAgrawal instead of setting `ws.Cells(6,1).Value` the way your code is doing. set `ws.Cells(6,1).Validation` instead, following the VBA example. All Excel documentation of this sort assumes you are programming in VBA so you need to learn to transpose solutions into Python. – BoarGules Jan 07 '19 at 11:46
  • @BoarGules I am not able to understand that VBA code.. If possible can you please help. – Saurabh Agrawal Jan 08 '19 at 11:04

1 Answers1

4

What you are doing isn't working because this line

ws.Cells(6,1).Value = "["GREEN", "YELLOW", "RED", "WHITE", "NOT SURE"]" //I want drop down here

is setting the value of the cell, just like the previous lines did. (Or rather, attempting to set it: that line contains two syntax errors, one in the quoting and one in the comment.)

But you don't want to set the value of the cell, you want to apply validation to the cell. So you need to set attributes of the object ws.Cells(6,1).Validation.

Taking just the code inside your try...except clause, that would look like this:

xl = Dispatch("Excel.Application")   
xl.Visible = 0  # Not really such fun to watch because the code below closes down Excel
                # straightaway. xl.Visible = 1 will just show a screen flicker.
wb = xl.Workbooks.Open(Filename=path1)

ws = wb.Worksheets(1)

ws.Cells(1,1).Value = "GREEN"
ws.Cells(2,1).Value = "YELLOW"
ws.Cells(3,1).Value = "RED"
ws.Cells(4,1).Value = "WHITE"
ws.Cells(5,1).Value = "NOT SURE"

# Set up validation
val = ws.Cells(6,1).Validation
val.Add(Type=3, AlertStyle=1, Operator=1, Formula1="=Sheet1!A1:A5")
val.IgnoreBlank = -1
val.InCellDropdown = -1
val.InputTitle = ""
val.ErrorTitle = ""
val.InputMessage = ""
val.ErrorMessage = ""
val.ShowInput = -1
val.ShowError = -1

wb.Close(SaveChanges=True)
xl.Quit()

The lines that set up the validation follow exactly the example in the reference given in my comment. The objects that win32com gets from Excel are not Python objects: they are thin Python wrappers around VBA objects, and these VBA objects follow their own conventions, not Python's. So the Python code follows the VBA exactly, except for syntax. The only differences are cosmetic.

  1. .Add gets parentheses because functions in Python have to have them (VBA methods don't).
  2. Named parameters to methods get a Python = not a VBA :=.
  3. Constants like xlBetween represent integer values; you can find the values on MSDN.
  4. VBA defines True as -1. 1 or True will probably also work: I didn't try.
  5. Python doesn't have an equivalent of VBA's with statement so val has to be explicit in assignments like val.ErrorMessage = "" instead of implicit as in VBA.

This is the result I got.

Excel 2016 screenshot of drop-down list

BoarGules
  • 16,440
  • 2
  • 27
  • 44
  • Ahhh that's what I was missing in my code.. Thank you so much for your help BoarGules. But seems like `val.IgnoreBlank = True` isn't working because if cell in blank then it's still showing in drop down. – Saurabh Agrawal Jan 09 '19 at 05:09
  • It only appears not to work. *Ignore Blank* does not mean that Excel will ignore blank cells in the named range you supply in `Formula1` and construct a drop-down list without them, as you seem to expect. It means that Excel will not complain about a blank value in the cell when blank is not one of the options in the drop-down list. https://www.mrexcel.com/forum/excel-questions/599304-data-validation-list-doesnt-ignore-blank-cells.html – BoarGules Jan 09 '19 at 08:26
  • Thanks for showing me some key points. Btw `win32com` internally using `COM` object which I want to avoid. Is there any other way to access full excel functionality without `COM` object. – Saurabh Agrawal Jan 09 '19 at 09:04
  • I take it you have discovered that you can't deploy this solution to machines that don't have Excel installed. The `win32com` module uses COM. That is its purpose, as its name suggests. The `xlwings` module also uses COM, but, as its name suggests, is Excel-specific. You could try `openpyxl`. It has at least some support for validation (https://openpyxl.readthedocs.io/en/stable/validation.html) but I can't say if its support extends to full Excel functionality. The only software that can do *everything* that Excel does is Excel itself, and COM is the only way to access that programmatically. – BoarGules Jan 09 '19 at 09:19
  • How to add list of record in dropdown, instead of Formula1="=Sheet1!A1:A5". – praveen kumar Mar 23 '20 at 07:37
  • I don't think it's possible to do that in Excel itself. It follows that you can't use com to do it, either. – BoarGules Mar 23 '20 at 07:40