繁体   English   中英

Excel VBA验证列表设置默认值

[英]Excel VBA Validation List set Default Value

我已经制定了以下代码(减去Dim and 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

这没什么大不了的,因为我能够将默认值设置为正确的值,因此一切正常。 但是,最好选择默认值作为选中下拉列表时的焦点,而不是始终选择列表中的第一项。

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

任何有关如何实现此目标的建议将不胜感激。

问候,

韦恩

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

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中。

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

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

listitem的范围是“ Opleiding”

在您的VBA代码中:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM