【发布时间】:2021-02-17 16:57:23
【问题描述】:
我有一些数据:
对于每一列,我想计算最近一年的平均值。在下面的示例中,我想计算 2020 年的数据,因此第 164、165 和 166 行。结果应该出现在第 163 行。
但是,我想要的不仅仅是结果,我还想要公式,以便用户可以看到正在计算的内容,但我不能。也许相关:我正在使用德语 Excel。我尝试使用.FormulaLocal 和MITTELWERT(德语为AVERAGE),但我认为我犯了另一种错误。对于.Formula 和.FormulaLocal,我在.Formula 的行中遇到运行时错误13(类型)。
Sub FormulaLeased(ByVal fRow As Long, ByVal lCol As Long, ws As Worksheet)
Dim i As Long
Dim iCol As Long
'manually setting values for this example:
fRow = 164
lCol = 7
Set ws = ActiveSheet
With ws
Select Case Mid(.Cells(fRow, "A").Value, 4, 2) 'Determining the most recent quarter
Case "12"
i = 3
Case "09"
i = 2
Case "06"
i = 1
Case "03"
i = 0
End Select
For iCol = 2 To lCol
'---works, but only shows the result, not the forumla:
'.Cells(fRow - 1, iCol).Value = Application.WorksheetFunction.Average(.Range(.Cells(fRow, iCol), .Cells(fRow + i, iCol)))
'---results in type error:
.Cells(fRow - 1, iCol).Formula = "= Application.WorksheetFunction.Average(" & .Range(.Cells(fRow, iCol).Address(False, False) & ":" & .Cells(fRow + i, iCol).Address(False, False)) & ")"
'---trying to use .FormulaLocal -> Type error
'.Cells(fRow - 1, iCol).FormulaLocal = "= MITTELWERT(" & .Range(.Cells(fRow, iCol).Address(False, False) & ":" & .Cells(fRow + i, iCol).Address(False, False)) & ")"
Next iCol
End With
End Sub
【问题讨论】:
-
Application.WorksheetFunction不适用于.Formula或.FormulaLocal。.Formula需要英文公式,就像您在单元格中一样,.FormulaLocal需要本地化公式(德语),就像您在单元格中一样。 -
@Pᴇʜ 我试过
.Cells(fRow - 1, iCol).Formula = "= AVERAGE(" & .Range(.Cells(fRow, iCol).Address(False, False) & ":" & .Cells(fRow + i, iCol).Address(False, False)) & ")",仍然得到同样的错误。与我已经在原帖中尝试过的MITTELWERT相同。