Excel VBA – 多个子对不同的项目做同样的事情

这是我的第一个问题,所以要温柔,我是在Excel中使用VBA的全新。 我发现了一个完成我想要的子程序:根据特定单元格的input或值更改形状的颜色。

Private Sub Worksheet_Change(ByVal Target As Range) 'Updateby Extendoffice 20160704 If Intersect(Target, Range("A1")) Is Nothing Then Exit Sub If IsNumeric(Target.Value) Then If Target.Value < 10 Then ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbRed ElseIf Target.Value >= 10 And Target.Value < 20 Then ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbYellow ElseIf Target.Value >= 20 And Target.Value < 30 Then ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbBlue Else ActiveSheet.Shapes("Oval 1").Fill.ForeColor.RGB = vbGreen End If End If 

我想要做的是运行同样的确切的子最多5个形状的值出现在单元格A1:A5。 我确定这很容易,但我似乎无法find我find的文档中的解决scheme。 有没有办法做到这一点,或所有他们都必须在自己的模块?

几乎是你的以下代码:

 If Intersect(Target, Range("A1")) Is Nothing Then Exit Sub 

退出,如果更改的单元格不是A1。 如果值在A1:A5中,你必须详细说明一下,不允许退出。 这可以通过以下方式来实现:

 If Intersect(Target, Range(Cells(1, 1), Cells(5, 1))) Is Nothing Then Exit Sub 

Cells(1,1)A1Cell(5,1)A5 。 他们都宣布允许范围的开始和结束。

以下是MDSN中Worksheet_Change事件的文档 – https://msdn.microsoft.com/en-us/library/office/ff839775.aspx

我想我会用Select...Case而不是If...Then

不知道如何识别要更新的五个形状中的哪一个,所以我使用了目标行号 – 更新第1行,并更新了椭圆1,第2行更新了椭圆2等。

使用@Vityatabuild议的相交,除了在相交前面放置Not关键字,它会颠倒TRUE / FALSE的答案 – 我试着让每个过程都有一个出口点,这样所有的代码都会stream到最后,需要执行的线。 我已经用Else语句突出显示了这一点,只是持有一个评论(如果你愿意,可以删除)。

 Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Range(Cells(1, 1), Cells(5, 1))) Is Nothing Then 'Value is the default property of Target so we can just say 'Target'. If IsNumeric(Target) Then 'Select Case works a bit like If...Else If....Else...End If. 'You can string expressions together: Case 10 To 19, 39 To 49, >100, <>102 Select Case Target Case Is < 10 'Use the Target row to define the name of the shape. 'Pass that and the colour to the UpdateShape procedure. UpdateShape Shapes("Oval " & Target.Row), vbRed Case 10 To 19 UpdateShape Shapes("Oval " & Target.Row), vbYellow Case 20 To 29 UpdateShape Shapes("Oval " & Target.Row), vbBlue Case Else UpdateShape Shapes("Oval " & Target.Row), vbGreen End Select End If Else 'Do nothing - Target is not within A1:A5. End If End Sub Private Sub UpdateShape(ShapeRef As Shape, RGBColor As Long) ShapeRef.Fill.ForeColor.RGB = RGBColor End Sub