2012-03-12 27 views
0

我会尽我所能来做到这一点。我有一个Excel工作表,需要对单元格进行求和,直到达到目标。然后这些单元需要一个内部颜色集。然后重置计算,然后继续下去,直到下一轮细胞等于目标。内部应该设置为不同的颜色。这将在整个范围内交替。我拥有它约90%,但第二种颜色只突出了集合的开始,然后继续第一种颜色。预先感谢您的任何指针Excel 2007 VBA Cell.interior基于连续单元格计算交替对目标

我:

Sub calctarget() 
    Dim x As Variant 
    Dim xsub As Variant 
    Dim total As Double 
    Dim y As Variant 
    Dim target As Double 
    Dim RunTotal As Double 

    target = 44500 

    If RunTotal < target Then y = 0 
    RunTotal = 0 
    For Each y In Range("a1:a15") 
     On Error Resume Next 
     RunTotal = RunTotal + y.Value 
     If RunTotal < target Then 
      y.Interior.ColorIndex = 4 
     End If 
     If RunTotal > target Then 
      RunTotal = RunTotal - y 
      If y.Offset(-1, 0).Interior.ColorIndex = 4 Then 
       RunTotal = 0 
       If RunTotal = 0 Then y.Interior.ColorIndex = 5 
       RunTotal = RunTotal + y 
      End If 
     End If 
    Next y 
End Sub 
+0

我已经改变了缩进以使其更容易阅读 - 你能检查这是你的意思吗? – assylias 2012-03-12 15:10:44

回答

1

这也许是你所需要的(它交替的颜色每次达到目标时间,并携带平衡向前如有):

Sub calctarget() 
    Dim c As Range 
    Dim target As Double 
    Dim runTotal As Double 
    Dim currentColor As Long 

    target = 44500 
    currentColor = 4 

    For Each c In Range("a1:a15") 
     If IsNumeric(c) Then 
      runTotal = runTotal + c 
     End If 
     If runTotal >= target Then 'Target reached 
      currentColor = IIf(currentColor = 4, 5, 4) 'alternate colors (4 and 5) 
      runTotal = runTotal - target 'maybe you want to start from 0 again? 
     End If 
     c.Interior.ColorIndex = currentColor 
    Next c 
End Sub 
+0

酷,让我更接近一步。虽然计算结果稍微偏离了一点点。第二套运行>然后目标。这基本上是建立一个卡车装载出成套的产品重量。小区必须连续求和才能遵循出站时间表。所以一旦细胞总数尽可能接近目标而没有超过,这将是一个负载。下一组将再次从0开始,直到达到接近目标。冲洗/重复。这让我非常接近刚刚弄清楚计算。谢谢 – PCGIZMO 2012-03-12 15:44:26

+0

@PCGIZMO你只需要改变'runTotal = runTotal - target'到'runTotal = 0' – assylias 2012-03-12 15:46:40

+0

{https://开头的文档。 google.com/open?id=0BzGnV1BGYQbvMERWU3VkdGFTQS1tYXpXcU1Mc3lmUQ} – PCGIZMO 2012-03-12 18:29:33

相关问题