WorksheetFunction.Average 并粘贴到新的 sheet

WorksheetFunction.Average and paste to new sheet

我在 sheet1 上有一组数据,我试图取每 48 个值的平均值并将其粘贴到 sheet2 上。我收到 运行 次错误“1004”:无法获得工作 sheet 函数 class 的平均值 属性。我尝试寻找不同的解决方案,但无法想出一个。我能得到一些关于我的代码的帮助吗?当我的代码只是取平均值并粘贴在相同的 sheet.

上时,它就起作用了
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

完成:

编写以下循环

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

此代码将显示 Sheet Daily 中 48 行的集合的平均值 Column A