问题描述
我有一个速度值的Excel电子表格(请参见下面的链接),其中散布了一些空白。我试图遍历每一行,并返回每一行中最长的一组连续非空白单元格的范围。我最终将使用范围地址来执行其他功能(即,对该范围内的值求平均值)。我以前使用下面的代码来计算一个范围内的列数,但是还没有弄清楚如何仅计算非空白单元格并继续在同一行中计数。
ColumnCount = Cells(1,Columns.Count).End(xlToLeft).Column
谢谢!任何帮助将非常感激! 玛丽
解决方法
您可以使用Do Until
循环和If
语句从头到尾遍历整行。下面是一行的示例(目前没有Excel,因此无法检查)。 maxLength
变量存储每次迭代时找到的最大值。 Cells(1,currCol).Value = ""
用于检查连续范围是否仅由1个单元格组成(否则,它将计算空范围加上2个非空单元格再加上1个单元格)。
Dim maxLength as Integer
maxLength = 0
currCol = 1
totalCol = Columns.Count
If Cells(1,currCol).Value = "" Then
currCol = Cells(1,currCol).End(xlToRight).Column
End If
Do Until currCol = totalCol
prevCol = currCol
If Cells(1,prevCol + 1).Value = "" Then
maxLength = WorkSheetFunction.Max(maxLength,1)
Else
currCol = Cells(1,currCol).End(xlToRight).Column
maxLength = WorkSheetFunction.Max(maxLength,currCol - prevCol + 1)
End if
currCol = Cells(1,currCol).End(xlToRight).Column
Loop