Excel - 单击依赖数据验证组合框

时间:2017-11-29 13:09:26

标签: excel validation combobox onclick

我在目前使用BeforeDoubleClick的工作表上有代码。此代码将组合框放在双击的任何包含数据验证公式的单元格上。组合框采用了公式。

我喜欢这样,因为您获得了数据验证列表,但您也可以选择让用户输入组合框并获取数据验证选项的自动完成功能。

工作表本身有两个数据验证区域,一个用于State,一个用于City。城市数据验证取决于对州的选择。

我真的不喜欢用户每次想要更改选择时都必须双击。如果他们可以单击并让它弹出来就会很好。

感谢任何帮助!

工作表代码: (来自http://www.contextures.com/xlDataVal11.html#works) ((他们有另一个链接(http://www.contextures.com/xlDataVal14.html)显示如何在单击时执行此操作,但是当我尝试添加= INDIRECT(允许依赖数据验证)的部分时,它不起作用。))< / p>

'==========================
Private Sub Worksheet_BeforeDoubleClick _
  (ByVal Target As Range, _
    Cancel As Boolean)
Dim str As String
Dim cboTemp As OLEObject
Dim ws As Worksheet
Set ws = ActiveSheet

Set cboTemp = ws.OLEObjects("TempCombo")
  On Error Resume Next
  With cboTemp
  'clear and hide the combo box
    .ListFillRange = ""
    .LinkedCell = ""
    .Visible = False
  End With
On Error GoTo errHandler
  If Target.Validation.Type = 3 Then
    'if the cell contains
      'a data validation list
    Cancel = True
    Application.EnableEvents = False
    'get the data validation formula
    str = Target.Validation.Formula1
    str = Right(str, Len(str) - 1)

    'for simple INDIRECT function (English)
    ' e.g. =INDIRECT(B2)
    'will create dependent list of items
    If Left(str, 4) = "INDI" Then
      lSplit = InStr(1, str, "(")
      str = Right(str, Len(str) - lSplit)
      str = Left(str, Len(str) - 1)
      str = Range(str).Value
    End If

    With cboTemp
      'show the combobox with the list
      .Visible = True
      .Left = Target.Left
      .Top = Target.Top
      .Width = Target.Width + 15
      .Height = Target.Height + 4
      .ListFillRange = str
      .LinkedCell = Target.Address
    End With
    cboTemp.Activate
    'open the drop down list automatically
    Me.TempCombo.DropDown
  End If

errHandler:
  Application.EnableEvents = True
  Exit Sub

End Sub
'=========================================
Private Sub TempCombo_LostFocus()
  With Me.TempCombo
    .Top = 10
    .Left = 10
    .Width = 0
    .ListFillRange = ""
    .LinkedCell = ""
    .Visible = False
    .Value = ""
  End With
End Sub
'====================================
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

ValidationSample Sheet

State Data Validation

City Data Validation

Tables and NameManager

1 个答案:

答案 0 :(得分:0)

哇,答案很简单......

我将其更改为“Worksheet_SelectionChange(ByVal Target as Range)” (摆脱取消为布尔) 然后注释出“取消=真”

希望这可以帮助有人下线!