WorksheetFunction.Average并粘贴到新工作表

时间:2016-06-30 17:47:38

标签: excel vba worksheet-function

我在sheet1上有一组数据,我试图取每48个值的平均值并将其粘贴到sheet2上。我得到一个运行时错误'1004':无法获得WorksheetFunction类的Average属性。我试着寻找不同的解决方案,但无法想出一个。我能从代码中获得一些帮助吗?我的代码只是在平均值和粘贴在同一张纸上时起作用。

Dim wb As Workbook
Dim j As Long, i As Long, irow As Integer, lastrow1 As Long, lastcol1 As Long

lastrow1 = Range(Sheets("HalfHour").Cells(5, 5), Sheets("HalfHour").Cells(5, 5).End(xlDown)).Count
lastcol1 = Range(Sheets("HalfHour").Cells(5, 5), Sheets("HalfHour").Cells(5, 5).End(xlToRight)).Count
Set wb = ActiveWorkbook
    With Worksheets("Daily")
        For j = 5 To lastcol + 5
            For i = 5 To lastrow1 + 5 Step 48
                wb.Worksheets("Daily").Cells(irow, a - 1).Value = Application.WorksheetFunction.Average(wb.Worksheets("HalfHour").Range(Cells(i, j), Cells(i + 47, j)))
                irow = irow + 1
            Next i
            If Cells(i, j).Value = "" Then
                GoTo done
            End If
        Next j
    End With

完成的:

1 个答案:

答案 0 :(得分:0)

编写以下循环

For i = 5 To lastrow1 + 5 Step 48
    wb.Worksheets("Daily").Cells(irow, a - 1).Value = Application.WorksheetFunction.Average(wb.Worksheets("HalfHour").Range(Cells(i, j), Cells(i + 47, j)))
    irow = irow + 1
Next i

作为

For i = 5 To lastrow1 + 5 Step 48
    Set myRange = Range(wb.Worksheets("HalfHour").Cells(i, j), wb.Worksheets("HalfHour").Cells(i, j).Cells(i + 47, j))
    If Application.WorksheetFunction.Count(myRange) > 0 Then
        wb.Worksheets("Daily").Cells(irow, a - 1).Value = Application.WorksheetFunction.Average(myRange)
    End If
    irow = irow + 1
Next i

注意:Dim myRange As Range写在您声明变量的位置。

您可以编写完整的代码:

Sub Demo()
    Dim wb As Workbook
    Dim j As Long, i As Long, irow As Integer, lastrow1 As Long, lastcol1 As Long
    Dim myRange As Range

    irow = 1
    a = 2

    lastrow1 = Range(Sheets("HalfHour").Cells(5, 5), Sheets("HalfHour").Cells(5, 5).End(xlDown)).Count
    lastcol1 = Range(Sheets("HalfHour").Cells(5, 5), Sheets("HalfHour").Cells(5, 5).End(xlToRight)).Count
    Set wb = ActiveWorkbook
    For j = 5 To lastcol + 5
        For i = 5 To lastrow1 + 5 Step 48
            Set myRange = Range(wb.Worksheets("HalfHour").Cells(i, j), wb.Worksheets("HalfHour").Cells(i, j).Cells(i + 47, j))
            If Application.WorksheetFunction.Count(myRange) > 0 Then
                wb.Worksheets("Daily").Cells(irow, a - 1).Value = Application.WorksheetFunction.Average(myRange)
            End If
            irow = irow + 1
        Next i
        If Cells(i, j).Value = "" Then
            GoTo done
        End If
    Next j
done:
End Sub

此代码将在Daily中的工作表Column A中显示48行的平均值。