سؤال

this's my first question and I'm a little bad at python and english too, I hope you understand...

I'm trying to cycle through the rows in an excel column. The last lines return None, what's wrong with my code?

import win32com.client

excel = win32com.client.Dispatch("Excel.Application")

for n in range(1,200):
    n=repr(n)
    cell = "b"+ n
    lis = (excel.ActiveWorkbook.Activesheet.Range(cell))
    if lis != "":
        print(lis)
    else:
        print("There's nothing here")

It prints None for the white rows, instead of There's nothing here.

Thank you very much for your help.

هل كانت مفيدة؟

المحلول

None != "". You should be testing with the is not operator:

if lis is not None:

Note that you shouldn't be using != None as others have suggested. From PEP8

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

EDIT: as per the discussion in the comments, lis should be assigned as follows:

lis = excel.ActiveWorkbook.Activesheet.Range(cell).GetValue()

نصائح أخرى

Because an empty row will return a None value instead of an empty string.

So, compare it to the None type instead:

if lis is not None:
    print(lis)
else:
    print("There's nothing here")

This should work just fine.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top