2012-03-12 52 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

相關問題