2014-11-14 12 views
0

我在Excel VBA項目中使用了一個組合框,它使用一系列單元格作爲項目列表。我在其中使用了一個過濾器,這樣,無論何時輸入值,列表都會縮小到包含該字符串的項目,並顯示下拉列表。但是,出現問題時,顯示下拉菜單時,不能使用導航鍵在項目內滾動。一旦按下向下鍵,下拉列表將被再次過濾。如何在不選擇列出項目的情況下使用組合框keydown事件

我猜想它的發生是因爲下側鍵同時關注物品,也在選擇它。因此,combobox_change事件被自動調用。

有沒有辦法讓我可以停止keydown事件自動選擇一個項目,但只能通過它們滾動?

+0

如果列表進行排序,組合框會自動提示下一個有效選項..你不會需要一個過濾器。但無論如何,如果你想擁有這個過濾器函數和keydown事件,你可以在你的keyDown事件中排除導航鍵。無論是與否或選擇的情況下...如果不是KeyCode = 48然後.. – 2014-11-14 15:07:20

+1

感謝您的建議,但我已經嘗試過,但問題沒有解決。 Vba在使用向下鍵進行聚焦時自動選擇該項目。有什麼辦法可以阻止它嗎? – Prantosh 2014-11-15 09:11:32

回答

1

編輯答案:

現在已經建立了自己的表,並與這些思想工作,具有諷刺意味的Application.EnableEnable只有在特定情況下幫助,因爲Combobox_Change()事件仍然禁用(事件觸發或者似乎是的情況下,在最小)。我發現的基本想法涉及操縱KeyCodes並設置標誌。我下面的例子包括使用ComboBox稱爲TempCombo和VBA內TempCombo_KeyDown()事件的表後運行的代碼(我已經削減了我的東西,例如用途):

Option Explicit 
Dim Abort as Boolean 

Private Sub TempCombo_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) 
    Select Case KeyCode 
     Case 38 'Up 
      If TempCombo.ListIndex <= 0 Then KeyCode = 0 'ignore "Up" press if already on the first selection, or if not on a selection 
      Abort = True 
      If Not KeyCode = 0 Then ' If on a selection past the first entry 
       KeyCode = 0 
      'Manually choose next entry, cancel key press 
       TempCombo.ListIndex = TempCombo.ListIndex - 1 
      End If 
      Me.TempCombo.DropDown 
     Case 40 'Down 
      If TempCombo.ListIndex = TempCombo.ListCount - 1 Then Keycode = 0 
     ' This method was from the discussion I linked, prevents "falling off the bottom of the list" 
      Abort = True 
      If Not KeyCode = 0 Then ' If on a selection before the last entry 
       KeyCode = 0 
      'Manually choose next entry, cancel key press 
       TempCombo.ListIndex = TempCombo.ListIndex + 1 
      End If 
      Me.TempCombo.DropDown 
    End Select 
    Abort = False 
End Sub 

Private Sub TempCombo_Change() 
    If Abort Then Exit Sub ' Stop Event code if flag set 
    Abort = True 
    ' sets the flag until finished with commands to prevent changes made by code triggering the event multiple times 

    ' ~~~ Insert Code you want to run for other cases here ~~~ 

    Abort = False 
End Sub 

我用Abort變量作爲一個標誌​​以防止事件代碼的多次觸發,並允許鍵不更改鏈接單元格的文本結果,從而防止更新我的動態範圍。確保兩個子例程位於ComboBox所在的工作表上!

所以這是我爲此做的一個骨架,如果有人發現問題請告訴我,但我希望這可以幫助某人。


老回答

我不知道有多少,這將真正幫助,如果我有 聲譽,我只想提出這個作爲一個評論,因爲這確實不是 有資格作爲答案。然而,我有同樣的問題,並試圖回答這個問題,偶然發現了 。我希望,在代碼中的一個 微軟的幫助頁面:http://answers.microsoft.com/en-us/office/forum/office_2007-customize/disable-userform-combobox-change-event-when-arrow/598b44a1-dcda-4a2c-8e12-2b84762f98ae?db=5

似乎看KeyDown事件的向上和向下箭頭 和配對與ComboBox_Change事件將讓您隔離 他們,然後當您上下按下 來導航列表時,防止更新組合框。

我建議通過OP的後續文章來看,這是令人難以置信的 信息,並幫助我適應我自己的情況。 還注意UserForm和一般Excel VBAcode之間的差異,對於 實例Me.EnableEvents對於UserForm將需要爲 Application.EnableEvents一般excel!

我現在知道這是舊的,但在此情況下,任何人幫助,祝你好運!

相關問題