找到工作表上的第一个完全空行

时间:2016-06-01 22:59:55

标签: excel-vba vba excel

需要一个函数,它从具有备用填充单元格的工作表中返回第一个完全空行(没有值,没有公式,没有空格)。不需要填写任何一列。

我试过这个,但我甚至可以编译它:

Public Donations As Worksheet
Set Donations = Sheets("Sheet2")

Function getEmptyRow() As Long
   Dim lastCol As Long, lastRow As Long, maxRow As Long
   Dim col As Long
   Dim r As Variant

   lastCol = Donations.Cells(1, Columns.Count).End(xlToLeft).Column
   For col = 1 To lastCol Step 1
      lastRow = Donations.Cells(Rows.Count, col).End(xlUp).row
      maxRow = Application.WorksheetFunction.max(maxRow, lastRow)
   Next col
   getEmptyRow = maxRow + 1
End Function

3 个答案:

答案 0 :(得分:3)

使用EntireRow(这是非常有用的让我告诉你)并从A1开始逐行计数是一种非常基本的方法。

这将在即时窗口中告诉您:

Sub findemptyrow()                       '''Psuedo Code
Application.ScreenUpdating = False       'turns off annoying blinky
Range("a1").Activate                     'start at beginning   
While a <> 1                             'keep going
  If Application.CountA(ActiveCell.EntireRow) = 0 Then  'is it blank?
  Debug.Print "Row " & (ActiveCell.Row) & " is blank."   'it is
  a = 1                                   'stop going  
  End If
  ActiveCell.Offset(1).Activate           'next cell
Wend                                      'do it all over again  
Application.ScreenUpdating = True         'back to normal settings
End Sub

使ScreenUpdating False可以加快速度,即使行数为10k也是如此。

答案 1 :(得分:0)

Range.Find method可能是最方便的方法。查找通配符(What:=Chr(42)),从A1开始(After:=.Cells(1, 1),向后搜索(SearchDirection:=xlPrevious),逐行搜索(SearchOrder:=xlByRows).Row),查看公式(LookIn:=xlFormulas)因为那会找到第一个值或公式;如果公式返回一个空字符串(xlValues),则查看""可能不正确。

Option Explicit
Public Donations As Worksheet

Sub test()
    Set Donations = Worksheets("Sheet2")
    Debug.Print getNextEmptyRow(Donations)
End Sub

Function getNextEmptyRow(ws As Worksheet)
    With ws.Cells
        getNextEmptyRow = .Find(What:=Chr(42), After:=.Cells(1, 1), LookIn:=xlFormulas, _
                                SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row + 1
    End With
End Function

您无法在模块代码表的声明区域中设置Donations。在代码表的声明区域(顶部)中声明公共变量,但在子或函数中设置变量。

如果您想要&#39;下一个空行&#39; ,请不要忘记在返回的行中添加1。

答案 2 :(得分:0)

使用`Range:

SpecialCells方法的另一种方法
Option Explicit

Sub Test()
    Debug.Print "Last row on Sheet1 is: " & FirstCompletelyEmptyRow(Sheet1)
End Sub

Function FirstCompletelyEmptyRow(ByRef wsTarget As Worksheet) As Long
    FirstCompletelyEmptyRow = wsTarget.Range("A1").SpecialCells(xlCellTypeLastCell).Row + 1
End Function