2012-11-29 53 views
1

我知道代碼可能不是很好,但我仍然在學習VBA。響應單元格值更改的自動執行

我已經創建了一個工作表來組織我的大學課程列表,但我試圖讓代碼自動執行,當我更改前兩列中的值時。

第一列中的「x」選擇該項目作爲完成的課程,從所需的總小時數中減去該課程的學分。第二列中的「S」和一些數字表示一個學期,並總結每學期要學習的學分數,例如,如果我在「工程學學習和職業」旁邊輸入「S1」,那麼它將採用該課程1學時,並將其添加到整個學期的總小時數中。

這兩個代碼是完全相互獨立的。

截圖工作表: http://i.imgur.com/G850X.png

代碼:

Private Sub Calculations() 

    Dim creditsLeft As Integer creditsLeft = 130 

    For i = 3 To 43 
     If Cells(i, 1).Value = "x" Then creditsLeft = (creditsLeft - Cells(i, 8)) Next i 

    Range("J3").Value = creditsLeft 


    Dim S1creds, S2creds, S3creds, S4creds, S5creds, S6creds As Integer 

    For i = 3 To 43 
     If Cells(i, 2).Value = "S1" Then S1creds = (S1creds + Cells(i, 8)) 
     If Cells(i, 2).Value = "S2" Then S2creds = (S2creds + Cells(i, 8)) 
     If Cells(i, 2).Value = "S3" Then S3creds = (S3creds + Cells(i, 8)) 
     If Cells(i, 2).Value = "S4" Then S4creds = (S4creds + Cells(i, 8)) 
     If Cells(i, 2).Value = "S5" Then S5creds = (S5creds + Cells(i, 8)) 
     If Cells(i, 2).Value = "S6" Then S6creds = (S6creds + Cells(i, 8)) 
    Next i 

    Range("J9").Value = "Sem 1 Hrs: " 
    Range("J10").Value = "Sem 2 Hrs: " 
    Range("J11").Value = "Sem 3 Hrs: " 
    Range("J12").Value = "Sem 4 Hrs: " 
    Range("J13").Value = "Sem 5 Hrs: " 
    Range("J14").Value = "Sem 6 Hrs: " 

    Range("K9").Value = S1creds 
    Range("K10").Value = S2creds 
    Range("K11").Value = S3creds 
    Range("K12").Value = S4creds 
    Range("K13").Value = S5creds 
    Range("K14").Value = S6creds 

    End Sub 
+2

看到'Worksheet_Change'事件。這將幫助你實現你的目標。如果卡住了,請回復卡住的地方。 –

回答

3

你甚至不需要VBA爲。

I3:=130-SUMIF(A3:A43,"x",H3:H43)
K9:=SUMIF(B3:B43,"S1",H3:H43)
K10:=SUMIF(B3:B43,"S2",H3:H43)
K11:=SUMIF(B3:B43,"S3",H3:H43)
K12:=SUMIF(B3:B43,"S4",H3:H43)
K13:=SUMIF(B3:B43,"S5",H3:H43)
K14:=SUMIF(B3:B43,"S6",H3:H43)

+0

謝謝肖恩!甚至不知道有一個SUMIF – mmiles19

相關問題