Excel Vba表上的平均值

时间:2018-05-09 19:54:12

标签: excel vba excel-vba

我有一张1,800,000行和100列的表格。第一列是时间列,列中的每个单元对应的增量为0.002秒(或多或少),总计3600秒。我试图将每个其他列中的值的平均值设为1s步(我将1s步中的所有值相加,我除以步数,得到平均值)。然后我清除所有的值,我只是复制每1步获得的值。我的代码有效,但我猜有更好的方法可以做到这一点,因为由于数据量很大,这种方法非常慢。

Option Explicit
Sub AverageResult()

'-------dall altro script
Dim LastRowInca As Long
Dim FirstRowInca As Long
Dim LastRow As Long
Dim FirstRow As Long
'-------dall'altro script


Dim i As Long
Dim t1 As Long
Dim t2 As Long
Dim variable As Long
Dim avg As Long
Dim numSampling As Long
numSampling = 0
Dim ColumnSelected As Long



'lunghezza della colonna del tempo
Dim timeColumn As Long
timeColumn = Sheets(1).UsedRange.Rows(Sheets(1).UsedRange.Rows.Count).Row

'numero totale di colonne
Dim totColumn As Long
totColumn = Cells(1, Columns.Count).End(xlToLeft).Column
totColumn = Sheets(1).UsedRange.Columns(Sheets(1).UsedRange.Columns.Count).Column

FirstRowInca = 2

For ColumnSelected = 2 To totColumn
t1 = 0
t2 = 1
variable = 0
avg = 0
numSampling = 0

Debug.Print "colonna selezionata"; ColumnSelected
For i = FirstRowInca To timeColumn

Debug.Print "calcolo la riga"; i; "colonna"; ColumnSelected
' definisco l'intervallo di un secondo in cui deve fare la media
If Cells(i, 1).Value > t1 And Cells(i, 1).Value <= t2 Then
    'calcolo la prima variabile se la cella non è vuota
    If Cells(i, ColumnSelected).Value <> "" Then
    variable = variable + Sheets(1).Cells(i, ColumnSelected).Value

    'Setto la cella come vuota
    Cells(i, ColumnSelected).Value = ""

    'Segno il divisore
    numSampling = numSampling + 1

'Se la cella come vuota
    ElseIf Cells(i, ColumnSelected).Value = "" Then
    Debug.Print "Vuoto"
    End If
Else
'Faccio il valore medio e passo all'intervallo successivo
If numSampling <> 0 Then
avg = variable / (numSampling)
'metto nella cella precedente il valore
Cells(i - 1, ColumnSelected).Value = avg
Debug.Print "la media è"; avg; "l'intervallo era"; t1; "a"; t2; "la riga è"; i
variable = 0
avg = 0
numSampling = 0
t1 = t1 + 1
t2 = t2 + 1
If Cells(i, ColumnSelected).Value <> "" Then
    variable = variable + Sheets(1).Cells(i, ColumnSelected).Value
    'Setto la cella come vuota
    Cells(i, ColumnSelected).Value = ""
    'Segno il divisore
    numSampling = numSampling + 1

'Se la cella come vuota
    ElseIf Cells(i, ColumnSelected).Value = "" Then
    Debug.Print "Vuoto"
    End If
    End If
End If

Next i
Next ColumnSelected





End Sub

1 个答案:

答案 0 :(得分:0)

我想建议一种不同的方法 - 一种没有VBA的方法,只有普通的Excel公式 您必须在数据旁边添加两列。在此示例中,我在列A中有一个时间戳,在列B中有一个值。列C的公式为=TRUNC(A1),列D的公式为=IF(C1<>C2,AVERAGEIF(C:C,C1,B:B),"")

Example