我的代码需要一些帮助。基本上,我只需要平均一列中的3个值,然后继续该模式,直到没有更多值即可。有人可以帮忙吗?
我想求平均值,例如A1:A3,A4:A6 ..等等,直到没有更多值为止。平均结果为B1:B2。
Sub DLSaverage()
Dim i As Long, j As Long, k As Long, l As Long, m As Long, myRange As Range
Sheets("DLS Data").Select
i = 2
j = 3
k = 4
Do While Cells(i, 3).Value <> ""
'l = Cells(i, 2).Value
'm = Cells(k, 2).Value
'Cells(j, 22).Value = [Average (l : m)]
i = i + 3
j = j + 1
k = k + 3
Set myRange = Range("L" & i & ":L" & k)
Cells(j, 22).Value = Application.Average(myRange)
Loop
End Sub
答案 0 :(得分:0)
Sub TestMe()
Dim curRow As Long
curRow = 1
Do While Worksheets(1).Cells(curRow, 1) <> ""
With Worksheets(1)
.Cells(curRow, 4).Formula = "=AVERAGE(A" & curRow & ":C" & curRow & ")"
curRow = curRow + 1
End With
Loop
End Sub
上面的代码将用=Average(A1:C1)
的公式填充D列:
答案 1 :(得分:0)
我建议
Option Explicit
Sub testAverage()
Const Window As Long = 3
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim Target As Range
Set Target = ws.Range("A1", ws.Cells(ws.Rows.Count, "A").End(xlUp))
Dim iRow As Long
For iRow = 1 To Target.Rows.Count Step Window
ws.Cells((iRow \ Window) + 1, "C").Value = Application.WorksheetFunction.Average(ws.Cells(iRow, "A").Resize(RowSize:=Window))
Next iRow
End Sub
请注意,目标行ws.Cells((iRow \ Window) + 1, "C").Value
是用整数除 (iRow \ Window) + 1
计算的,不是正常除法。
答案 2 :(得分:0)
这可以在没有vba的情况下完成:
将此内容放入C1并复制下来:
=IFERROR(AVERAGE(INDEX(A:A,(ROW(1:1)-1)*3+1):INDEX(A:A,(ROW(1:1)-1)*3+3)),"")
答案 3 :(得分:0)
使用数组
Option Explicit
Public Sub GetAverages()
Dim ws As Worksheet, numOutputRows As Long, arr(), i As Long
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
arr = Application.Transpose(.Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row))
Dim outputArray(), rowCounter As Long
ReDim outputArray(1 To Round(UBound(arr) / 3, 0))
For i = 1 To UBound(arr) Step 3
rowCounter = rowCounter + 1
outputArray(rowCounter) = Application.WorksheetFunction.Average(arr(i), arr(i + 1), arr(i + 2))
Next
ws.Cells(1, 2).Resize(UBound(outputArray), 1) = Application.Transpose(outputArray)
End With
End Sub