Vin*_*nzz 6 vba data-validation microsoft-excel
我在 Excel 文档中有一些单元格是从命名范围填充的(数据/验证/列表源 = MyNamedRange):
这里,A1:A3 范围被命名为 Foobar
B5:B6 正在数据验证中,其源设置为“Foobar”
我希望能够更新单元格的 A2 内容,从 Bar 到 Quux,并自动看到 B5 单元格的内容更新为 Quux,因为它的源已更改。
它可能通过宏执行,但我不知道如何编码。
请问有什么提示吗?
这看起来很危险,但我看不出有什么问题。基本上,如果您在 Foobar 中更改任何内容,它会搜索工作表上具有数据验证的每个单元格。如果 DV 指向 Foobar 并且该值不在列表中,则它一定是已更改的值。它适用于我有限的测试。如果您发现任何缺陷,请告诉我。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rCell As Range
Dim rFound As Range
'Only run this when a cell in Foobar is changed
If Not Intersect(Target, Me.Range("Foobar")) Is Nothing Then
'Go through every data validation cell in the sheet
For Each rCell In Me.Cells.SpecialCells(xlCellTypeAllValidation).Cells
'if the DV in the cell points to foobar
If rCell.Validation.Formula1 = "=Foobar" Then
'See if the cell's value is in the Foobar list
Set rFound = Me.Range("Foobar").Find(rCell.Value, , xlValues, xlWhole)
'If it's not in the list, it must be the one that
'changed, so changed it
If rFound Is Nothing Then
Application.EnableEvents = False
rCell.Value = Target.Value
Application.EnableEvents = True
End If
End If
Next rCell
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
请注意,这位于工作表的模块中,而不是标准模块中。与往常一样,在工作簿的副本上测试代码。
归档时间: |
|
查看次数: |
5971 次 |
最近记录: |