簡體   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