excel vba用于循环更改步骤

时间:2016-07-05 15:43:56

标签: excel vba excel-vba for-loop

我正在尝试编写一个将每日价值平均为月度值的程序。我发现的困难是每个月都有不同的月份,所以我想我必须改变循环中的步骤。我的程序运行正常,但正确步骤的逻辑有点偏。

lastrow2 = Range(Sheets("Daily").Cells(5, 3), Sheets("Daily").Cells(5, 3).End(xlDown)).Count
lastcol2 = Range(Sheets("Daily").Cells(5, 3), Sheets("Daily").Cells(5, 3).End(xlToRight)).Count

irow2 = 5
cnt = 5
Set wb = ActiveWorkbook
    For j2 = 3 To lastcol1 + 3                              'number of columns in the dataset
nextmo:
        If Sheets("Daily").Cells(i2, 2) = 1 Or Sheets("Daily").Cells(i2, 2) = 60 Or Sheets("Daily").Cells(i2, 2) = 121 Or Sheets("Daily").Cells(i2, 2) = 182 Or Sheets("Daily").Cells(i2, 2) = 213 Or Sheets("Daily").Cells(i2, 2) = 274 Or Sheets("Daily").Cells(i2, 2) = 335 Then
            daysofthemo = 31
        ElseIf Sheets("Daily").Cells(i2, 2) = 91 Or Sheets("Daily").Cells(i2, 2) = 152 Or Sheets("Daily").Cells(i2, 2) = 244 Or Sheets("Daily").Cells(i2, 2) = 305 Then
            daysofthemo = 30
        ElseIf Sheets("Daily").Cells(i2, 2) = 32 Then
            daysofthemo = 28
        End If

        For i2 = cnt To lastrow1 + 5 Step daysofthemo         'number of rows in the dataset

            'Will now take the average of one month and paste onto worksheet called "monthly"
            Set myRange2 = Range(wb.Worksheets("Daily").Cells(i2, j2), wb.Worksheets("Daily").Cells(i2 + daysofthemo - 1, j2))
            If Application.WorksheetFunction.Count(myRange2) > 0 Then
                wb.Worksheets("Monthly").Cells(irow2, j2).Value = Application.WorksheetFunction.Average(myRange2)
            End If
            irow2 = irow2 + 1
            cnt = i2 + daysofthemo
            goto nextmo
        Next i2
    Next j2

我在if语句之前和之后都有msgbox。 输出应该是: 274,31,305,30,335,31,1,31等。

但是现在输出是:274,31,305,30,336,30,2,33等等。

想到这个新代码,经过测试但仍然不对。

1 个答案:

答案 0 :(得分:0)

intDaysInMonth=DateDiff("d", DateSerial(Year(dtDate), Month(dtDate), 1), WorksheetFunction.EoMonth(dtDate, 0)) + 1