Finding first blank row, then writing to it

后端 未结 8 1876
小鲜肉
小鲜肉 2020-12-02 00:30

I need to find the first blank row in a workbook and write information to (row, 1) and (row, 2). I think I\'m currently pretty stuck...

Function WriteToMaste         


        
8条回答
  •  無奈伤痛
    2020-12-02 00:45

    If you mean the row number after the last row that is used, you can find it with this:

    Dim unusedRow As Long
    unusedRow = Cells.SpecialCells(xlCellTypeLastCell).Offset(1, 0).Row
    

    If you mean a row that happens to be blank with data after it... it gets more complicated.

    Here's a function I wrote which will give you the actual row number of the first row that is blank for the provided worksheet.

    Function firstBlankRow(ws As Worksheet) As Long
    'returns the row # of the row after the last used row
    'Or the first row with no data in it
        Dim rw As Range
        For Each rw In ws.UsedRange.Rows
            If rw.Address = ws.Range(rw.Address).SpecialCells(xlCellTypeBlanks). _
                Address Then
    
                    firstBlankRow = rw.Row
                    Exit For
            End If
        Next
        If firstBlankRow = 0 Then
            firstBlankRow = ws.Cells.SpecialCells(xlCellTypeLastCell). _
                        Offset(1, 0).Row
        End If
    End Function
    

    Usage example: firstblankRow(thisworkbook.Sheets(1)) or pass any worksheet.

    Edit: As ooo pointed out, this will error if there are no blank cells in your used range.

提交回复
热议问题