excel VBA _set子范围以计算移动平均值

lf3rwulv  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(138)

请让我知道如何正确地设置一个表的部分范围,作为计算其简单移动平均值的来源,子范围的子范围。(数据源表命名为“Skandi”,记录平均值的目标表命名为“MovAvg”)
错误源于VBA脚本的以下声明,在模块中以红色标记:

Sub movingaverage()

Dim MovAvg As Worksheet: Set MovAvg = Sheets("MovAvg")
Dim Skandi As Worksheet: Set Skandi = Sheets("Skandi")
Dim xHeti As Long: xHeti = 6      ' time span for calculating averages
Dim sz As Long: sz = 35       ' Nr of columns in table
Dim Col As Long                   
Dim Row As Long                  

For Col = 1 To sz
    For Row = 1 To Skandi.Range("namedRange").Rows.Count
     Dim fCell As Range: Set fCell = Skandi.Range("namedRange").Cells(Row, Col)    
     Dim lCell As Range: Set lCell = Skandi.Range("namedRange").Cells(Row + xHeti, Col)
     Dim AvgRng As Range: Set AvgRng = Range(fCell, lCell)                                                                         
        MovAvg.Cells(7 + Row, Col) = WorksheetFunction.Average(AvgRng)     ' fault here. Marked yellow !                                                  
       
    Next Row
Next Col
End Sub

我在这个网站上查看了相关的问答,但这些还没有为我提供救助。

8cdiaqws

8cdiaqws1#

(at最少)2个代码问题:
a)在使用iFirstiLast作为范围iRange的参数之前,您需要设置它们。在您的代码中,它们被声明为Nothing,并且您不能从Nothing创建Range
B)在VBA中从2个范围创建范围的正确语法是用逗号分隔2个范围参数,而不是:(这将是Excel语法)。

Dim iRange As Range

For Col = 1 To sz
    For Row = 1 To Skandi.Range("namedrange").Rows.Count
         Set iFirst = Skandi.Range("namedrange").Cells(Row, Col)
         Set iLast = Skandi.Range("namedrange").Cells(Row + xHeti, Col)
         Set iRange = Range(ifirst, ilast)
         MovAvg.Cells(7 + Row, Col) = WorksheetFunction.Average(iRange)
     Next Row
Next Col

P.S.你有一个奇怪的命名惯例:为什么要在范围变量名前面加上前缀i

相关问题