2014-09-01 81 views
1

我正在填充一些數據驗證下拉列表,它們的值在表中。
我有一個按鈕(指向用戶窗體的鏈接)爲用戶添加項目到表中。輸入新值後,表格的Worksheet_Change代碼對錶格進行排序。
所以如果一個值被刪除,表格就會調整大小。是否可以延遲Worksheet_Change代碼? Excel Vba

但現在我的問題是,當用戶窗體中的按鈕被點擊首先一行被添加到表中,然後值被添加到該行。在添加值之前,Worksheet_Change已經全部檢測到新的空行並將其刪除。
是否有可能推遲這一點,或有人知道更好的解決方案?

爲用戶窗體代碼:

Private Sub butAddProject_Click() 

    Dim listSheet As Worksheet 
    Dim listTable As listObject 
    Dim newRow As ListRow 
    Dim ProjectName As String 

    ProjectName = txtAddProject.Text 

    Set listSheet = Sheets("Projects-Tasks") 
    Set listTable = listSheet.ListObjects(1) 

    If ProjectName <> "" Then 
     Set newRow = listTable.ListRows.Add 
     newRow.Range(1, 1).Value = ProjectName 
    Else 
     MsgBox "Enter a project name first!" 
    End If 

    txtAddProject.Text = "" 
    formAddProject.Hide 

End Sub 

最後的Worksheet_Change代碼:

Private Sub Worksheet_Change(ByVal Target As Range) 

    Dim ws As Worksheet 
    Dim strList As String 
    Set ws = Sheets("Projects-Tasks") 
    strList = Cells(2, Target.Column).listObject.Name 

    If strList <> "" Then 
     Application.ScreenUpdating = False 
      With ListObjects(strList).Sort 
       .SortFields.Add _ 
        Key:=Cells(3, Target.Column), _ 
        SortOn:=xlSortOnValues, _ 
        Order:=xlAscending 
       .Header = xlYes 
       .MatchCase = False 
       .Orientation = xlTopToBottom 
       .SortMethod = xlPinYin 
       .Apply 
      End With 

     With ws.ListObjects(strList) 
      .Resize .DataBodyRange.CurrentRegion 
     End With 

    End If 

    Application.ScreenUpdating = True 

End Sub 

在此先感謝!

+0

你可以檢查'Target.Value =「」'? – RubberDuck 2014-09-01 14:09:24

+0

不好意思,你是怎麼說的? – 2014-09-01 14:10:05

+0

我的意思是,如果更改的單元格(即「目標」)爲空,是否可以簡單地繞過其餘的邏輯? – RubberDuck 2014-09-01 14:25:03

回答

2

變故關閉,同時增加新的行:

If ProjectName <> "" Then 
    application.enableevents = False 
    Set newRow = listTable.ListRows.Add 
    application.enableevents = True 
    newRow.Range(1, 1).Value = ProjectName 
Else 

我想你還是希望它進行排序,當你添加新的價值,所以我重新設置,增加了新值前行事件。

+0

謝謝你的代碼即時尋找! – 2014-09-01 14:47:14

+0

值得注意的是,您可能需要添加一個錯誤處理程序,以確保事件始終處於打開狀態。 – RubberDuck 2014-09-01 15:13:47

1
Private Sub butAddProject_Click() 

    Dim listSheet As Worksheet 
    Dim listTable As listObject 
    Dim newRow As ListRow 
    Dim ProjectName As String 

    Application.EnableEvents=False 

    ProjectName = txtAddProject.Text 

    Set listSheet = Sheets("Projects-Tasks") 
    Set listTable = listSheet.ListObjects(1) 

    If ProjectName <> "" Then 
     Set newRow = listTable.ListRows.Add 
     newRow.Range(1, 1).Value = ProjectName 
    Else 
     MsgBox "Enter a project name first!" 
    End If 

    txtAddProject.Text = "" 
    formAddProject.Hide 

    Application.EnableEvents=True 


End Sub 
+0

感謝這就是代碼即時尋找! – 2014-09-01 14:46:41