2017-03-15 40 views
1

我是新來的,希望你在我面臨的挑戰中有所幫助。如何使用VBA循環訪問每月數據?

我正在使用VBA for Excel的項目。我有來自14個月的數據,並希望將每個月的最後一個值除以同一個月的第一個值。本月的第一個工作日可以是任何一天,最後一天也可以。我編寫了下面的代碼來查找並突出顯示每個月的最後一天,並且它很有用。

sub find_lastrow() 
    Dim lrow As Long 
    Dim i As Long 
    Dim data As Date 
    Dim next_day As Date 

    lrow = Cells(Rows.Count, "A").End(xlUp).Row 

    For i = 2 To lrow 

     data = Cells(i, "A") 
     next_date = Cells(i, "A").Offset(1, 0) 

     'finding and painting last day of each month and last day of each year 

     If Month(next_date) = Month(data) + 1 Or _ 
      Year(next_date) = Year(data) + 1 Then 

      Range(Cells(i, "A"), Cells(i, "K")).Select 

      With Selection.Interior 
       .Pattern = xlSolid 
       .PatternColorIndex = xlAutomatic 
       .ThemeColor = xlThemeColorLight2 
       .TintAndShade = 0.799981688894314 
       .PatternTintAndShade = 0 
      End With 

     End If 
End sub 

但是,我很難將每月的第一個值除以相應月份的最後一個值。我非常感謝你的幫助。

enter image description here

回答

0

首先,你需要完成你的循環。其次,由第一值劃分的最後一個值,只需創建一個變量來保持的第一個值,直到到達包含的最後一行行 - 那麼它可用於劃分:

sub find_lastrow() 
    Dim lrow As Long 
    Dim i As Long 
    Dim data As Date 
    Dim next_day As Date 
    Dim StartValue As Double 

    lrow = Cells(Rows.Count, "A").End(xlUp).Row 
    StartValue = Cells(2, "B").Value 

    For i = 2 To lrow 

     data = Cells(i, "A") 
     next_date = Cells(i + 1, "A") 

     'finding and painting last day of each month and last day of each year 

     If Month(next_date) = Month(data) + 1 Or _ 
      Year(next_date) = Year(data) + 1 Then 

      Cells(i, "C").Value = Cells(i, "B").Value/StartValue 
      'Set up start value for next month 
      StartValue = Cells(i + 1, "B").Value 

      With Range(Cells(i, "A"), Cells(i, "K")).Interior 
       .Pattern = xlSolid 
       .PatternColorIndex = xlAutomatic 
       .ThemeColor = xlThemeColorLight2 
       .TintAndShade = 0.799981688894314 
       .PatternTintAndShade = 0 
      End With 

     End If 
    Next 
End Sub 
+0

你的代碼工作。非常感謝你! – Raphy