当python循环找到2个连续的空单元格时,中断python循环

当python循环找到2个连续的空单元格时,中断python循环,python,excel,loops,automation,break,Python,Excel,Loops,Automation,Break,我想使用循环计算Excel表中的行和列,当遇到2个(或更多)连续的空单元格时,循环应该停止运行 row_count=0 col_count=0 for a in range(1,temp.max_row+1): if temp.cell(row=a,column=2).value!=None: row_count= row_count+1 else: break for b in range(2,temp.max_column+1): if tem

我想使用循环计算Excel表中的行和列,当遇到2个(或更多)连续的空单元格时,循环应该停止运行

row_count=0
col_count=0

for a in range(1,temp.max_row+1):
   if temp.cell(row=a,column=2).value!=None:
       row_count= row_count+1
   else:
       break
for b in range(2,temp.max_column+1):
   if temp.cell(row=8,column=b).value!=None:
       col_count=col_count+1
   else:
       break
print(row_count)
print(col_count)

但是,我无法使用所使用的方法获得正确的结果。

您需要在每次迭代中检查两个相邻的单元格:

for a in range(1,temp.max_row+1):
   # Check if the cell is not empty
   if temp.cell(row=a, column=2).value is not None: 
       row_count = row_count + 1

   # Else the cell is empty, check if the next one is also empty
   elif temp.cell(row=a + 1, column=2).value is None: 
       break

for b in range(2,temp.max_column+1):
   if temp.cell(row=8, column=b).value is not None:
       col_count = col_count + 1
   elif temp.cell(row=8, column=b + 1).value is None:
       break

谢谢你回答我的问题。我做了一些更改,下面的代码似乎最适合我的数据。-(代码的目的是在excel工作表中测量表的维度(该工作表包含多个这样的表)。因此,如果遇到(例如)两个连续的空单元格,它必须在到达另一个表之前停止计数。)

# A) For 2 consecutive empty cells- 

#for rows: 
for a in range(4, temp.max_row+1):
    if (temp.cell(row=a, column=2).value==None and temp.cell(row=a+1, column=2).value==None): #check if current cell & the following cell is not empty. if empty, it stops counting & exits the loop.
        break
    else:
        row_count=row_count+1


#for columns: 
for b in range(2,temp.max_column+1):
    if (temp.cell(row=20, column=b).value==None and temp.cell(row=20,column=b+1).value==None):
        break
    else:
        col_count = col_count+1