我在工作簿中一张工作表(Sheet2)的 D 列中有一些值,这些值是通过公式得出的,以获取 C 列单元格中较长值的最后部分。双击后,较长的值会自动输入到 C 列中。在单独的工作表(Sheet5)上,我在该工作表的 C 列中有一个值列表。如果 Sheet2 的 D 列中的任何值等于 Sheet5 的 C 列中的任何值,我希望 Sheet2 的 F 列中的单元格变为红色。一旦 Sheet2 中的 F 列单元格变为红色,根据 D 列中的值,我希望红色单元格变为可点击,这将把用户带到另一个工作表,其中列出了与 D 列中的值相关的参考值。下面的代码就是这样做的。但是,我想避免对需要参考代码的不同值进行硬编码,因为我希望将来会在 Sheet5 的 C 列列表中添加或删除一些需要参考代码的值。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range: Set c = Union(Range("D7:D446"), Range("F7:F446"))
Dim CellF As Range, CellD As Range, Cell As Range
If Not Application.Intersect(c, Range(Target.Address)) Is Nothing Then
Set CellF = Range("F" & Target.Row)
Set CellD = Range("D" & Target.Row)
If CellF.Value <> "" And getMacroDictionary.Exists(CellD.Text) Then
CellF.Interior.ColorIndex = 3
Else
CellF.Interior.ColorIndex = 0
End If
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim key As String, dic As Object
Set sourceRange = Nothing
If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
Set sourceRange = Target
Set dic = getMacroDictionary
key = Target.Offset(0, -2).Value2
If dic.Exists(key) Then Application.Run dic(key)
End If
End Sub
Function getMacroDictionary() As Object
Dim dic As Object
Set dic = CreateObject("SCripting.Dictionary")
dic.Add "1000GP", "gotoref1"
dic.Add "1000MM", "gotoref2"
dic.Add "19FEST", "gotoref3"
dic.Add "20IEDU", "gotoref4"
dic.Add "20ONLC", "gotoref5"
dic.Add "20PART", "gotoref6"
dic.Add "20PRDV", "gotoref7"
dic.Add "20SPPR", "gotoref8"
dic.Add "22DANC", "gotoref9"
dic.Add "22LFLC", "gotoref10"
dic.Add "22MEDA", "gotoref11"
dic.Add "530CCH", "gotoref12"
dic.Add "60PUBL", "gotoref13"
dic.Add "74GA01", "gotoref14"
dic.Add "74GA17", "gotoref15"
dic.Add "74GA99", "gotoref16"
dic.Add "78REDV", "gotoref17"
Set getMacroDictionary = dic
End Function
我认为避免硬编码的最佳方法是创建一个数组。在第一个子部分中,您将看到注释掉的代码片段,我尝试这样做,但我不确定如何调用不同的宏,因为它们与某些值相关联。
提前感谢你的帮助!