首页 文章

VBA在范围内找到第一个连续的空单元格

提问于
浏览
0

我发现这个很棒的代码可以找到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

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

1 回答

  • 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
    

相关问题