我找到了这个很棒的代码来查找this link列中的第一个空单元格。但是,如果我在值范围内有2个连续的空单元格,则此代码不起作用。当我想要第一个时,它只会选择第二个空单元格。连续的单元格可以是该范围内的任何位置,前2或中2或后2。此外,它可能是3,4,5连续单元格,因此我不能使用任何行计算公式。如果有人可以告诉我如何更改代码,我将非常感激。
Public Sub SelectFirstBlankCell()
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 6 'column F has a value of 6
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 3 To rowCount
currentRowValue = Cells(currentRow, sourceCol).Value
If IsEmpty(currentRowValue) Or currentRowValue = "" Then
Cells(currentRow, sourceCol).Select
End If
Next
End Sub
另外,刚刚发现如果我有多个非连续的空行,在这些范围内,在数据之间,它也会选择最后一个空行(而不是最后一行!)
答案 0 :(得分:1)
诀窍是如果检测到空单元格,则添加一个Exit For来打破循环。
另外,如果你想让你的代码更具可扩展性,我建议将sourceCol作为一个参数而不是在sub中定义。 这允许您为任何列
创建宏Public Sub SelectFirstFromF()
Call SelectFirstBlankCell()
End Sub
Public Sub SelectFirstFromB()
Call SelectFirstBlankCell(2)
End Sub
Sub SelectFirstBlankCell(Optional sourceCol as Integer = 6)
Dim rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 3 To rowCount
currentRowValue = Cells(currentRow, sourceCol).Value
If IsEmpty(currentRowValue) Or currentRowValue = "" Then
Cells(currentRow, sourceCol).Select
Exit For
End If
Next
End Sub