如何在VBA中找到第一个空单元?

时间:2016-10-28 09:13:53

标签: vba excel-vba excel

我的表格如下:
enter image description here

我有一个函数来获取A列中 LAST 空单元格的索引:

NextRow = Range("A" & Rows.Count).End(xlUp).Row + 1

此函数用于在第二个数组(Type2)上写入。

但是现在,我想要一个函数来获取A列中 FIRST 空单元格的索引。所以我去了这个网站:Select first empty cell我尝试调整代码但它是不起作用:

If Array= "Type1" Then
    Dim ws As Worksheet
    Set ws = ActiveSheet
    For Each cell In ws.Columns(1).Cells
       If IsEmpty(cell) = True Then NextRow = cell: Exit For 'ERROR 1004
    Next cell
End If
If Array= "Type2" Then 'It s works
    NextRow = Range("A" & Rows.Count).End(xlUp).Row + 1
End If

ActiveSheet.Range("A" & NextRow) = "TEST"

您能否帮助我修改我的代码以获得NextRow = IndexOf FIRST empty cell in A

4 个答案:

答案 0 :(得分:4)

您可以使用与获取最后一个相同的方法。

document.getElementById('ElementID').addEventListener('click', function(event){
   console.log(event);
});

答案 1 :(得分:1)

我这样做,它'工作:

If Array= "Type1" Then
       Dim ws As Worksheet
            Set ws = ActiveSheet
            For Each cell In ws.Columns(1).Cells
               If IsEmpty(cell) = True Then
                    NextRow = cell.Row
                    Exit For
                    MsgBox NextRow
                End If
            Next cell
    End If
    If Array= "Type2" Then 'It s works
        NextRow = Range("A" & Rows.Count).End(xlUp).Row + 1
    End If

    ActiveSheet.Range("A" & NextRow) = "TEST"

答案 2 :(得分:1)

你应该自下而上看看。

Find优于xlUp

Sub FindBlank()
    Dim ws As Worksheet
    Dim rng1 As Range
    Set ws = ActiveSheet
    Set rng1 = ws.Columns(1).Find("*", ws.[a1], xlFormulas, , xlByColumns, xlPrevious)
    If Not rng1 Is Nothing Then
        MsgBox "Last used cell is " & rng1.Address(0, 0)
    Else
        MsgBox ws.Name & " row1 is completely empty", vbCritical
    End If
End Sub

答案 3 :(得分:0)

我对某些答案采用了类似的方法,但目的是反复向下看该列,直到可以保证下面不再有填充的单元格。

我把它变成了一个小的功能,并放入了标准模块中:-

Public Function getFirstBlankRowNumberOnSheet(sht As Worksheet, Optional startingRef As String = "A1") As Long 'may get more than 32767 rows in a spreadsheet (but probably not!)
  Dim celTop As Range
  Dim celBottom As Range
  On Error Resume Next
  Set celTop = sht.Range(startingRef)

  Do
    Set celBottom = celTop.End(xlDown)
    Set celTop = celBottom.Offset(1) 'This will throw an error when the bottom cell is on the last available row (1048576)
  Loop Until IsEmpty(celBottom.value)

  getFirstBlankRowNumberOnSheet = celTop.Row

End Function

如果在行#1048576中恰好有内容,这将引发错误!具体细节取决于我假设的Excel版本(允许的最大行续)。