Excel VBA验证列表设置默认值

时间:2017-09-28 15:53:57

标签: excel vba list excel-vba validation

我已经计算出以下代码(减去Dim和Set部分,但WS1 = Sheet1和WS2 = Sheet2),它将我目标Excel工作表上的所有“验证列表”默认值设置为其引用表中的第一个项目:

'+++Work through the processing of the 'Validation Lists' in the Worksheet+++
For Each rngValList In WS1.Cells.SpecialCells(xlCellTypeAllValidation).Cells
    With rngValList
        If .Validation.Type = xlValidateList Then
            'Process those that should be set as the first value in the list.
            .Value = Range(Replace(.Validation.Formula1, "=", "")).Cells(1, 1)
        End If
    End With
Next rngValList

但是,在同一目标页面上有一个验证列表,我希望将默认值设置为列表中包含的其他项目。我可以通过单独计算项目然后更新选择验证列表值的单元格来实现这一点,这是有效的。但是,当我选择下拉按钮时,我真正想做的是让列表(很长)专注于目标默认项目。使用此方法,下拉列表中的第一项仍然是列表的焦点。

我尝试修改上面的代码来更改默认值(可能是一种太复杂的更改,但它有效),并且确实选择了正确的值。但是,当选中它时,下拉列表中的焦点仍然在列表中的第一个项目上。

我的修改后的代码如下:

    '+++Work through the processing of the 'Validation Lists' in the Worksheet+++
    For Each rngValList In WS1.Cells.SpecialCells(xlCellTypeAllValidation).Cells
        With rngValList
            If .Validation.Type = xlValidateList Then
                'If the Valdation List is Month End, then select the correct month date.
                If .Validation.Formula1 = "=LUT_MonthEnd" Then
                    'Set the Default End Month value to the correct Month.
                    i = 0
                    For Each rngSMList In WS2.Range(TS).Cells
                        i = i + 1
                        With rngSMList
                            If rngSMList = WS2.Range(DS) Then
                                 'Capture the counter at this point and exit to the rngValList Range Object.
                                 GoTo EndMthStop
                            End If
                        End With
                    Next rngSMList
EndMthStop:
                    .Value = Range(Replace(.Validation.Formula1, "=", "")).Cells(i, 1)
                Else
                    'Process those that should be set as the first value in the list.
                    .Value = Range(Replace(.Validation.Formula1, "=", "")).Cells(1, 1)
                End If
            End If
        End With

这不是什么大问题,因为我可以将默认值设置为正确的值,因此可以正常工作。但是,当选择下拉列表时,选择默认值为焦点,而不是始终是列表中的第一项,这将是很好的。

从概念上讲,我想我需要的是指向目标表列表中正确默认值的指针。

对于如何实现这一目标的任何建议都将非常感激。

此致

韦恩

2 个答案:

答案 0 :(得分:0)

这应该让你开始,以及我上面的评论。将以下代码粘贴到工作表对象(而不是模块)中。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Not Application.Intersect(Target, Range("A1")) Is Nothing Then
    Target.value = "Your Value"
End If

End Sub

Sub Worksheet_SelectionChange是每次选择新单元格时触发的事件。

Application.Intersect返回表示两个范围之间重叠的范围。

上面的示例假设您的列表位于单元格A1中。

目标是单击的单元格,因此我们将单元格的值设置为您希望在列表中选择的任何值。

答案 1 :(得分:0)

选择要放置列表项的单元格。

列表项的范围是“ Opleiding”

在您的VBA代码中:

selection.Value = Range("opleiding").Cells(2, 1)

结果是listItem的选定项目是“ Opleiding”范围内的第二个项目。

相关问题