您可以使用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