2016-12-04 73 views
1
Private Sub CommandButton1_Click() 

Dim Year    As Long 
Dim i As Long 

Year = 2008 
For Year = 2008 To ComboBox2.Value 
    For i = 2 To 200 Step 12 
     If ComboBox1.Value = "Januari" Then 
      Range("G15").Value = Sheets(3).Cells(i, 1).Value 
     ElseIf ComboBox1.Value = "Februari" Then 
      Range("G15").Value = Sheets(3).Cells(i + 1, 1).Value 
     ElseIf ComboBox1.Value = "Maret" Then 
      Range("G15").Value = Sheets(3).Cells(i + 2, 1).Value 
     ElseIf ComboBox1.Value = "April" Then 
      Range("G15").Value = Sheets(3).Cells(i + 3, 1).Value 
     ElseIf ComboBox1.Value = "Mei" Then 
      Range("G15").Value = Sheets(3).Cells(i + 4, 1).Value 
     ElseIf ComboBox1.Value = "Juni" Then 
      Range("G15").Value = Sheets(3).Cells(i + 5, 1).Value 
     ElseIf ComboBox1.Value = "Juli" Then 
      Range("G15").Value = Sheets(3).Cells(i + 6, 1).Value 
     ElseIf ComboBox1.Value = "Agustus" Then 
      Range("G15").Value = Sheets(3).Cells(i + 7, 1).Value 
     ElseIf ComboBox1.Value = "September" Then 
      Range("G15").Value = Sheets(3).Cells(i + 8, 1).Value 
     ElseIf ComboBox1.Value = "Oktober" Then 
      Range("G15").Value = Sheets(3).Cells(i + 9, 1).Value 
     ElseIf ComboBox1.Value = "November" Then 
      Range("G15").Value = Sheets(3).Cells(i + 10, 1).Value 
     ElseIf ComboBox1.Value = "Desember" Then 
      Range("G15").Value = Sheets(3).Cells(i + 12, 1).Value 
     End If 
    Next i 

Next Year 

Sheets(2).Range("I5").Value = ("CONTRACT SPOT") 

End Sub 

我想要它當我選擇januari 2009組合它顯示1,我選擇januari 2010組合它顯示13等等。請幫忙當語句符合條件時如何停止循環? -vba-excel

+0

到目前爲止它只顯示循環結束時的最後一個數字,例如,當我選擇januari 2009時顯示193 – Yomi

+0

combobox2.value範圍是2008至2050 – Yomi

+0

如果您想要退出For'循環時條件得到滿足,然後放入'If'語句的'Exit For'中。如果你解釋得更好,也許有一種方法來優化你的代碼 –

回答

1

So ComboBox1.Value有月份,ComboBox2.Value有年份。

而且要算 1 = 2009年1月 2 = 2009年2月 ... 13 = 2010年1月

然後,你需要做一些數學

Dim iMonth as Integer 

Dim iYear as Integer 
iYear = ComboBox2.Value 

Select Case ComboBox1.Value 
    Case "Januari" 
     iMonth = 1 
    Case "Februari" 
     iMonth = 2 
    Case "Maret" 
     iMonth = 3 
    Case "April" 
     iMonth = 4 
    Case "Mei" 
     iMonth = 5 
    Case "Juni" 
     iMonth = 6 
    Case "Juli" 
     iMonth = 7 
    Case "Agustus" 
     iMonth = 8 
    Case "September" 
     iMonth = 9 
    Case "Oktober" 
     iMonth = 10 
    Case "November" 
     iMonth = 11 
    Case "Desember" 
     iMonth = 12 
End Select 

Range("G15").Value = Sheets(3).Cells(iMonth + ((iYear - 2009) * 12), 1).Value 

我只是編碼這個動態,它可能有一些錯誤,讓我知道它是否工作! :)

+0

我希望它從另一個表中取值,2009年1月= 1,「1」僅僅是我創建的一個虛擬數字,以使其更容易。 – Yomi

+0

目前尚不清楚你想說什麼。因此,2009年1月的數據存儲在工作表1中,2009年2月存儲在工作表2中,依此類推? –

+0

不,所有月份和年份數據的組合都是商店3 – Yomi