Excel-VBA中的简单移动平均范围

时间:2016-09-12 14:12:15

标签: vba excel-vba average excel

此代码仅用于计算简单移动平均线。打开一个excel,在C行中创建一个从1到20的虚拟数组。我想创建一个函数,例如:SMA(C7,3)=它应该给出C5的平均值:C7。

很长一段时间回到VBA,无法确定下面代码中的错误。

Function sma1(rng As Range, N As Integer)
Set rng = rng.Resize(-N + 1, 0)
sma1 = Application.WorksheetFunction.average(rng)
End Function

3 个答案:

答案 0 :(得分:2)

  1. 避免将单元名称用作函数
  2. 修正了std::string dateStr1 = "2016-06-31 02:00:58"; // June 31 2016 does not exist std::string dateStr2 = "02:00:00"; std::istringstream date_s(dateStr1); struct tm date_c, date_c_cmp; date_s >> std::get_time( &date_c, "%Y-%m-%d %H:%M:%S" ); date_c_cmp = date_c; // store original to compare later std::time_t seconds1 = std::mktime( & date_c ); if(date_c.tm_year != date_c_cmp.tm_year // compare with original || date_c.tm_mon != date_c_cmp.tm_mon || date_c.tm_mday != date_c_cmp.tm_mday || date_c.tm_hour != date_c_cmp.tm_hour || date_c.tm_min != date_c_cmp.tm_min || date_c.tm_sec != date_c_cmp.tm_sec) std::cout << "invalid" << std::endl; std::istringstream date_s2( "2001-10-01 02:10:00" ); struct tm date_c2; date_s2 >> std::get_time( &date_c2, "%Y-%m-%d %H:%M:%S" ); std::time_t seconds2 = std::mktime( & date_c2 ); if(seconds1 > seconds2){ std::cout<<" Seconds1 is greater "<<seconds1<<std::endl; }else{ std::cout<<" Seconds2 is greater "<<seconds2<<std::endl; }
  3. 使用内部范围变量

  4. <击>     函数smal(rng As Range,N As Integer)As Variant         Dim rng2 As Range         设置rng2 = rng.Resize(N,1)         smal = Application.WorksheetFunction.Average(rng2)     结束功能

    修改#1:

    根据斯科特的评论:

    RESIZE()

答案 1 :(得分:0)

我假设你希望它旁边的列给你SMA(如下所示?):

enter image description here

如果是这样,下面会这样做并拖动它自动完成它到你的C列阵列的底部:

Sub SMA3()
    Range("D7").FormulaR1C1 = "=AVERAGE(R[-2]C[-1]:RC[-1])" 'This is a relative reference (left one cell and up two cells) - This give your three inputs
    Range("D7").AutoFill Destination:=Range("D7:D" & Range("C1048576").End(xlUp).Row) 'Autofills the SMA
End Sub

答案 2 :(得分:0)

只需一个FYI,可以使用现有公式完成:

 final DatabaseReference user = myRef.child("slavi");
 Query query = user.orderByChild("sortDate");

 query.addListenerForSingleValueEvent(new ValueEventListener() {
      public void onDataChange(DataSnapshot dataSnapshot) {
          for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
              System.out.println(userSnapshot.getKey());
          }

E1包含要包含的行数。

https://github.com/root-two/react-native-drawer