繁体   English   中英

在单元格中显示公式(平均函数)

[英]Display formula in cell (average function)

我有一些数据:

在此处输入图像描述

对于每一列,我想计算最近一年的平均值。 在下面的示例中,我想为 2020 年计算它,因此第 164、165 和 166 行。结果应出现在第 163 行。

但是,我不仅想要结果,还想要公式,以便用户可以看到正在计算的内容,但我不能。 可能相关:我正在使用德语 Excel。我尝试使用.FormulaLocalMITTELWERT (德语表示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需要您在单元格中编写的本地化公式(德语)。

所以这种方法是 go 的方法:

.Cells(fRow - 1, iCol).FormulaLocal = "= MITTELWERT(" & .Range(.Cells(fRow, iCol).Address(False, False) & ":" & .Cells(fRow + i, iCol).Address(False, False)) & ")"

但需要改为

.Cells(fRow - 1, iCol).FormulaLocal = "=MITTELWERT(" & .Cells(fRow, iCol).Address(False, False) & ":" & .Cells(fRow + i, iCol).Address(False, False) & ")"

不需要Range ,只需要 2 个单元格的地址。

请注意,此代码仅在您以德语 Excel 运行时才有效,因为MITTELWERT不会被翻译成其他本地化版本。 如果您计划您的代码也应该在法语 Excel 上运行,那么您将需要使用英语公式和.Formula 这将转换为任何本地化,因此适用于所有Excel 版本。 我强烈建议使用.Formula并将它们自己翻译成英文( https://excel-translator.de可能有帮助):

.Cells(fRow - 1, iCol).Formula = "=AVERAGE(" & .Cells(fRow, iCol).Address(False, False) & ":" & .Cells(fRow + i, iCol).Address(False, False) & ")"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM