gpt4 book ai didi

vba - Excel VBA 验证列表设置默认值

转载 作者:行者123 更新时间:2023-12-04 20:56:33 24 4
gpt4 key购买 nike

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

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

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

任何关于如何实现这一点的建议将不胜感激。

问候,

韦恩

最佳答案

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

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

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

关于vba - Excel VBA 验证列表设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com