Excel数据validationcombobox单击

我是非常新的编码…

工作表1有一个滚动列表中的数据validation,工作表2有它正在validation数据的列表。 我正在试图在表单1上创build一个combobox,在您键入时将自动填充,而不必input确切的名称。 下面的代码仅适用于数据列表与我试图打开combobox的工作表在同一张纸上。 任何想法如何改变代码,所以它将从表2中所有的数据列表所在的位置?

任何帮助将不胜感激

'========================================= Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim str As String Dim cboTemp As OLEObject Dim ws As Worksheet Set ws = ActiveSheet On Error GoTo errHandler If Target.Count > 1 Then GoTo exitHandler Set cboTemp = ws.OLEObjects("TempCombo") On Error Resume Next If cboTemp.Visible = True Then With cboTemp .Top = 10 .Left = 10 .ListFillRange = "" .LinkedCell = "" .Visible = False .Value = "" End With End If On Error GoTo errHandler If Target.Validation.Type = 3 Then 'if the cell contains a data validation list Application.EnableEvents = False 'get the data validation formula str = Target.Validation.Formula1 str = Right(str, Len(str) - 1) With cboTemp 'show the combobox with the list .Visible = True .Left = Target.Left .Top = Target.Top .Width = Target.Width + 15 .Height = Target.Height + 5 .ListFillRange = ws.Range(str).Address .LinkedCell = Target.Address End With cboTemp.Activate 'open the drop down list automatically Me.TempCombo.DropDown End If exitHandler: Application.ScreenUpdating = True Application.EnableEvents = True Exit Sub errHandler: Resume exitHandler End Sub '==================================== 'Optional code to move to next cell if Tab or Enter are pressed 'from code by Ted Lanham '***NOTE: if KeyDown causes problems, change to KeyUp Private Sub TempCombo_KeyDown(ByVal _ KeyCode As MSForms.ReturnInteger, _ ByVal Shift As Integer) Select Case KeyCode Case 9 'Tab ActiveCell.Offset(0, 1).Activate Case 13 'Enter ActiveCell.Offset(1, 0).Activate Case Else 'do nothing End Select End Sub '==================================== 

你有很多代码只是为了在活动工作表中填充一个combobox。 由于您正在使用Worksheet_Change事件,您不必将工作表设置为活动工作表,它已经是。 此示例代码将使用Sheet2中的单元格范围填充ComboBox1,代码和Combobox1位于Sheet1中。

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim ws As Worksheet, Rws As Long, Rng As Range 'ComboBox1 and this code are in Sheet1 Set ws = Sheets("Sheet2") 'sheet2 column 1 is the list to populate Combobox1 With ws 'set the list range Rws = .Cells(Rows.Count, "A").End(xlUp).Row Set Rng = .Range(.Cells(1, 1), .Cells(Rws, 1)) End With With ComboBox1 'populate the combobox .Clear .List = Rng.Value End With End Sub 

如果您可以放弃基于用户input的Excel自动完成function,则可以使用此处演示的单元validation(向后兼容旧版本):

从属下拉列表

或者在这里(对于新版本):

插入或删除一个下拉列表

这个好处是,它不需要代码,除非你想自动操纵列表。

使用combobox对象肯定是比较复杂的,所以你可以直接跳过,直到你的编码达到了对象所需的复杂度。

== ==编辑

OK,那么,2件事:这个代码(私人小组Worksheet_SelectionChange(BYVAL目标作为范围))适用于每次你点击一个新的单元格。 如果你的值没有太大的改变,你可以确保cbo只填充在workbook_open上,或者不活跃的东西。 但是,如果工作簿打开时combobox源数据频繁更改,则频繁刷新源代码将是值得的。

尝试命名你想要combobox来获取其数据的范围,并将ListFillRange指向指定的范围,如:

 .ListFillRange = "myNamedRange" 

然后,如果您的源代码增长或缩小,请合并基于更改重新定义命名范围的代码。