繁体   English   中英

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

[英]Excel VBA— Creating macro to change cell color and call other macros based on cell value

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

换句话说,例如,如果范围(D7:D446)=“ 1000ABC”,“ 1000EFG”或“ 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM