2016-10-28 210 views
0

我的片材的樣子:
enter image description here如何在VBA中找到第一個空單元格?

我有一個函數來獲取LAST空單元的索引在列A:

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

此功能對第二陣列寫(類型2) 。

但現在,我想一個函數來獲取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

你可以只使用你沒有得到最後一個相同的方法。

NextRow = Range("A1").End(xlDown).Row + 1 
+1

'xlDown'可能會誤導它,因爲它發現某個區域中的最後一個單元格 - 所以如果A2是空白的但使用了A3,則它不會到達A3。相反,如果範圍爲空,它將跳轉到工作表上的最後一行。 – brettdj

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" 
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 
相關問題