我有一个如下所示的数据集:
A 列始终包含升序数字(x-如图表中的时间[s])。
以下列包含数据。行数和列数每次都动态变化。 我想使用 vba 在 Excel 中做两件事:
我对代码有点挣扎(来源)。要让它发挥作用,还要找到最有效的方法。
'Option Explicit
Public Sub ExtractInformation()
'Calculate averages of columns
Dim lastCol As Long, lastRow As Long, m As Long, n As Long
Dim rng As Range
'Find the last column.
'Assumes the relevant column is the last one with data in row 5.
'With Sheets("Graphs")
lastCol = Sheets("Graphs").Cells(1, Columns.Count).End(xlToLeft).Column
lastRow = Sheets("Graphs").Cells(Rows.Count, "A").End(xlUp).Row
'End With
'Iterate the columns from 1 (ie "A") to the last.
For m = 1 To lastCol
With Sheets("Graphs")
'Define the data range for this column.
'Assumes last cell from bottom of sheet is the end of data.
Set rng = .Range(.Cells(1, m), .Cells(.Rows.Count, m).End(xlUp))
'Print the averages on row 125
.Cells(126, m) = WorksheetFunction.Average(rng) 'Print the averages on row 125
End With
Next
' For n = 1 To lastRow
' With Sheets("Graphs")
' 'Define the data range for this column.
' 'Assumes last cell from bottom of sheet is the end of data.
'' Set rng = .Range(.Cells(n, 1), .Cells(n, .Columns.Count).End(xlLeft))
' 'Print the averages on row 125
' .Cells(128, n) = WorksheetFunction.Average(rng) 'Print the averages on row 125
' End With
' Next
End Sub
此代码在某种程度上可以工作,除了带有注释的部分(取消注释会给出“错误1004”。此外,计算出的平均值与我手动计算的平均值不匹配。我认为这与不同的行数有关每列。
您的 1004 的原因很容易解释:当您使用
End
查找最后一列时,您需要使用 xlToLeft
,而不是 xlLeft
。常量 xlLeft
具有不同的含义(它用于文本对齐)。
我假设您想通过忽略空单元格来计算行/列的平均值。最简单的方法是使用
AverageIf
:AverageIf(rng, "<>")
将忽略所有没有值的单元格。AverageIf(rng, "<>0")
将忽略所有没有值或值为 0 的单元格
配备了它,您就可以清理代码了。请注意,我创建了一个小函数
getAgv
:它有一个错误处理程序,可以在范围不包含任何值时忽略运行时错误,并且它集中了计算逻辑,以便您不必重复公式。
另外,我假设您不想将 A 列的值添加到平均值计算中,因此我将它们排除在外。
Public Sub ExtractInformation()
Dim lastCol As Long, lastRow As Long, row As Long, col As Long
Dim rng As Range
'Find the last column.
'Assumes the relevant column is the last one with data in row 5.
With Sheets("Graphs")
lastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
lastRow = .Cells(Rows.Count, "A").End(xlUp).row
'Iterate the columns from 2 (ie "B") to the last.
For col = 2 To lastCol
Set rng = .Range(.Cells(1, col), .Cells(lastRow, col))
.Cells(lastRow+1, col) = getAvg(rng)
Next
'Iterate the rows from 1 last row
For row = 1 To lastRow
Set rng = .Range(.Cells(row, 2), .Cells(row, lastCol))
.Cells(row, lastCol + 1) = getAvg(rng)
Next
End With
End Sub
Public Function getAvg(rng As Range) As Variant
On Error Resume Next
getAvg = WorksheetFunction.AverageIf(rng, "<>")
On Error GoTo 0
End Function