2017-07-07 23 views
0

我想觸發一個事件如果用戶開始在B列輸入在最後一個空單元格的任何 我的代碼波紋管到目前爲止,但有一個不匹配範圍和不知道如何糾正它。檢測是列在最後一排被改變和火災事件

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim LastNonEmptyRow, LastRow, LastEmptyRow, LastValue As Long 

LastNonEmptyRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row 'finds the last NON-EMPTY Row in Columnt B 

LastEmptyRow = LastNonEmptyRow + 1' 
     If Not Intersect(Target, Range(LastEmptyRow)) Is Nothing Then ' LastEmptyRow needs to be as Range 
     MsgBox "You entered something in last empty row in column B!" 
     '...code to execute when data is entered in the last empty column 

    End If 
End Sub 

回答

0

您需要正確指定您的範圍。從這個變化:

Range(LastEmptyRow) 

要這樣:

Range("B" & LastEmptyRow) 

編輯:

考慮到上述帳戶與您的補充意見以來,代碼最終是這樣的:

Private oldValue As String 

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
    oldValue = Target.Value 
End Sub 

Private Sub Worksheet_Change(ByVal Target As Range) 
    Dim LastNonEmptyRow As Long 
    Dim LastRow As Long 
    Dim LastEmptyRow As Long 
    Dim LastValue As Long 

    If oldValue <> "" Then Exit Sub 

    LastNonEmptyRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row 'finds the last NON-EMPTY Row in Columnt B 
    LastEmptyRow = LastNonEmptyRow + 1 

    If Not Intersect(Target, Range("B" & LastNonEmptyRow)) Is Nothing Then ' LastEmptyRow needs to be as Range 
     MsgBox "You entered something in last empty row in column B - " & LastNonEmptyRow 
     '...code to execute when data is entered in the last empty column 
    End If 
End Sub 
+0

嗨,布萊恩,謝謝你的快速評論。您的方法不會再給出範圍問題,但代碼MsgBox不會觸發。我放置如果不相交(目標,範圍(「B」和LastEmptyRow))是沒有然​​後'LastEmptyRow需要作爲範圍 MsgBox「您在列B中的最後一個空行輸入的東西!和MsgBox不會觸發,但是如果我放置如果不相交(目標,範圍(「B」和LastNonEmptyRow))是沒有然​​後'LastEmptyRow需要作爲範圍代碼觸發最後一個非空和最後一個空單元格在列B – Serge

+0

嗨布賴恩,謝謝你的快速評論。您的方法不會再給出範圍問題,但代碼MsgBox不會觸發。我放置了'If Not Intersect(Target,Range(「B」&LastEmptyRow))是Nothing然後'LastEmptyRow需要作爲範圍MsgBox「你在B列的最後一個空行中輸入了一些東西! '和MSGBOX不火,但是如果我把'如果沒有相交(目標,範圍(「B」&LastNonEmptyRow))是沒有那麼'代碼火災的最後一個非空和空單元格 – Serge

+0

由當時的更改事件觸發空的單元不再是空的。當我改變你的代碼來使用LastNonEmptyRow時,它的工作原理就是我認爲你想讓它工作。我只得到1個事件,而對於剛剛更改的行,我只有1個事件。在我修改它之前,它已經空了。 –