【问题标题】:VBA find first of consecutive empty cells in rangeVBA在范围内找到第一个连续的空单元格
【发布时间】:2014-01-07 16:22:32
【问题描述】:

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

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

【问题讨论】:

    标签: vba


    【解决方案1】:

    诀窍是在检测到空单元格时添加 Exit For 以中断循环。

    另外,如果你想让你的代码更具可扩展性,我建议将 sourceCol 作为参数包含在 sub.xml 中。 这允许您为任何列创建宏

    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
    

    【讨论】:

    • 谢谢,我简直不敢相信这就是它所需要的.....另一件事,使用带有 sourceCol 作为参数的代码,宏无法运行,因为它不在我的宏中列表。为什么会这样?
    • OK 宏不能带参数并显示在宏列表中。我会更新我的答案以反映这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多