2014-01-07 67 views
0

我发现这个很棒的代码来找到this link列中的第一个空单元格。但是,如果在具有值的范围内有2个连续的空单元格,则此代码不起作用。它只会选择第二个空单元,当我想要第一个时。连续的单元格可以是范围内的任何位置,前2个或中间2个或后2个。此外,它可以是3,4,5个连续的单元格,因此我不能使用任何行计算公式。如果有人能告诉我如何更改代码,我会非常感激。VBA找到范围中连续的空单元格的第一个

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 

另外,刚刚发现,如果我有在范围之内,在数据之间的多个不连续的空行,它选择了最后一个空行,以及(不是最后一排!)

回答

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 
+0

谢谢,我不能相信这一切都需要.....还有一两件事,用你的代码与sourceCol作为参数,宏无法因为它不在我的宏列表中运行。为什么? – user2530250

+0

确定宏不能带参数并显示在宏列表中。 我会更新我的答案以反映这一点。 – serakfalcon

相关问题