Excel VBA--创建宏以更改单元格颜色并根据单元格值调用其他宏

时间:2017-06-05 20:17:50

标签: excel vba excel-vba switch-statement

我正在尝试编写一个调用不同宏并更改单元格颜色的宏。因此,如果整个列D(D4:D446)中的单元格等于某个值,则该宏将调用与该值相关联的单独宏。

换句话说,我想要的是,例如,范围内的任何或多个单元格(D7:D446)=" 1000ABC"," 1000EFG"或&#34 ; 1000HIJ"列F7:F446中的任何/所有单元格将变为红色,以向用户表明他们需要在F7:F446中的点击上以及当用户点击时列F中的单元格,它将调用我已创建的正确宏。

示例:如果单元格D25 =" 1000EFG"单元格F25将变为红色,当用户将光标移到单元格F25上并单击单元格F25时,它将将它们带到与值1000EFG相关联的宏。我已经创建了与这些特定值相关联的其他宏,我只需要F列中的单元格来改变颜色并变为可点击给用户,当单击时,调用某个宏。 我将发布我在下面尝试过的代码。很感谢任何形式的帮助。你们真棒,谢谢!

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
  Dim c As Range
  c = Range("D7:D446")
  For Each c In Intersect(ActiveCell, Range("D7:D446")) 'this is where the error is occuring
    Select Case c.Value
     Case "1000GP", "1000MM", "19FEST", "20IEDU", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
            Cells(c.Row, "F").Interior.ColorIndex = 3
      Case Else
        Cells(c.Row, "F").Interior.ColorIndex = 0
    End Select
  Next c
End Sub
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Cancel = True
      ' Now call the appropriate routine according to column C
      Select Case Target.Offset(0, -3).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
  End If
End Sub

1 个答案:

答案 0 :(得分:1)

调整Worksheet_Change事件的结构:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

  If Not Intersect(Target, Range("D7:D446")) is Nothing Then 

      Dim c As Range

      For Each c In Target 

          Select Case c.Value
              Case "1000GP", "1000MM", "19FEST", "20IEDU", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
                  Cells(c.Row, "F").Interior.ColorIndex = 3
              Case Else
                 Cells(c.Row, "F").Interior.ColorIndex = 0
          End Select

      Next c

 End If

End Sub