0

Dear, All.

If cells (i,5) does not have value, I want to delete the row in excel with python pywin32 at python 3.6.

this is my code.

def qms(self):
    fname = QtWidgets.QFileDialog.getOpenFileName(self)

    if fname[0]:
        self.Filename.setText(fname[0])
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible = True
        f = excel.Workbooks.Open(fname[0])
        fs = f.ActiveSheet
        lastrow = fs.UsedRange.Rows.Count

        for i in range(3, lastrow):
            if not fs.Cells(i,5).Value :
               fs.getCells().deleteRows(i-1,1,True)

        excel.Workbooks.save()
        excel.Quit()

I think there are problem in fs.getCells().deleteRow(i-1,1,True). I cannot understand. could you help me?

2 Answers 2

1
for i in range(lastrow, 2, -1):
    if fs.Cells(i,5).Value != ""
        fs.Rows(i).EntireRow.Delete()

or you can probably delete all at once:

fs.UsedRange.Offset(2).Columns(5).SpecialCells(4).EntireRow.Delete()

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-specialcells-method-excel

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for help me. but i can't understand fs.UsedRange.Offset(2).Columns(5).SpecialCells(4).EntireRow.Delete()
0
def qms(self):
    fname = QtWidgets.QFileDialog.getOpenFileName(self)

    if fname[0]:
        self.Filename.setText(fname[0])
        excel = win32com.client.Dispatch("Excel.Application")
        excel.Visible = True
        f = excel.Workbooks.Open(fname[0])
        fs = f.ActiveSheet
        lastrow = fs.UsedRange.Rows.Count

        for i in range(lastrow, 2, -1):
            if fs.Cells(i,5).Value == None or fs.Cells(i,5).Value == "":
                fs.Rows(i).EntireRow.Delete()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.