Excel VBAvalidation列表设置默认值

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

'+++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 

但是,在同一目标页面上有一个validation列表,我想将默认值设置为列表中包含的其他项目。 我可以通过单独计算项目,然后更新selectvalidation列表值的单元格来实现。 但是,当我select下拉button时,我真正想要做的就是将列表(很长)重点放在目标默认项目上。 使用这种方法,下拉列表中的第一项仍然是列表的焦点。

我尝试修改上面的代码来改变默认值(可能是一个太复杂的变化,但它的工作),它确实select了正确的值。 但是,下拉列表中的焦点仍然是列表中的第一项,当它被选中时。

我修改后的代码如下:

  '+++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 

这不是什么大问题,因为我可以将默认值设置为正确的值,所以事情很好。 但是,select下拉列表时,将选中的默认值设置为焦点,而不是始终显示列表中的第一项。

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

任何build议如何能够完成将是最感激的。

问候,

韦恩

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

 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是每次select新单元格时触发的事件。

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

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

Target是被点击的单元格,所以我们将单元格的值设置为您希望在列表中select的值。