如何在Excel VBA中切片矢量?

时间:2019-06-11 08:33:23

标签: arrays excel vba

我想获取Microsoft Excel-VBA中数组中仅几个项目的平均值。例如,取向量中每对数字的平均值:45 21 63 12 19.这里的主要问题是,我希望能够使数字数量动态,以便也可以始终取平均值每3个数字中。

我尝试使用The type of the expression must be an array type but it resolved to JSONArray函数或Index函数,但两者均无效。

Offset

此示例仅返回错误。

所需结果:

arravg的值是:

Dim arrMarks(1 To 5) As Long

arrMarks(1) = 45
arrMarks(2) = 21
arrMarks(3) = 63
arrMarks(4) = 12
arrMarks(5) = 19

length = UBound(arrMarks, 1) - LBound(arrMarks, 1) + 1

' take the average of m numbers

m = 3
m_length = length - (m-1)

Dim arravg(1 To m_length)

For i = 1 To m_length
    If (i + m) <= length Then
        arravg(i) = Application.WorksheetFunction.Average(arrMarks.Offset(m, 0))
    End If
Next i

我希望以某种方式编写代码,使Average(45, 21, 63) Average(21, 63, 12) Average(63, 12, 19) 可以用任何数字填充(只要m

1 个答案:

答案 0 :(得分:1)

获取连续的数组元素组中的平均值

允许灵活的组大小

示例呼叫

对您的帖子所做的唯一更改是,我使用了2维初始数组arrMarks,具有可能的优势,即您可以轻松地从给定范围(行)分配数据。

Sub ExampleCall()
ReDim arrMarks(1 To 1, 1 To 5)
arrMarks(1, 1) = 45
arrMarks(1, 2) = 21
arrMarks(1, 3) = 63
arrMarks(1, 4) = 12
arrMarks(1, 5) = 19

Dim arrAvg
arrAvg = getAverages(arrMarks, 3)           ' calculate averages in groups of 3 elements
Debug.Print "~> " & UBound(arrAvg) - LBound(arrAvg) + 1 & " averages: " & Join(arrAvg, "|")

End Sub

导致…

1) current group: 45, 21, 63               43 
2) current group: 21, 63, 12               32 
3) current group: 63, 12, 19               31,3333333333333 
~> 3 averages: 43|32|31,3333333333333

主要功能getAverages()

Function getAverages(arrData, Optional groupSize As Long = 2) As Variant()
' count array elements
  Dim lg As Long
  lg = UBound(arrData, 2) - LBound(arrData, 2) + 1

' take the average of m numbers
  Dim m_lg As Long
  m_lg = lg - (groupSize - 1)

  ReDim arrAvg(1 To m_lg)
  Dim temp, i As Long
  For i = 1 To m_lg
      If (i + groupSize) <= lg + 1 Then
          temp = Application.Index(arrData, Array(1), getElements(i, groupSize))
          arrAvg(i) = Application.WorksheetFunction.Average(temp)
          Debug.Print i & ") current group: " & Join(temp, ", "), arrAvg(i)
      End If
  Next i
' return averages
  getAverages = arrAvg
End Function

保存当前元素编号的辅助功能

Function getElements(ByVal start As Long, Optional ByVal groupSize As Long = 2)
ReDim temp(0 To groupSize - 1)
Dim i&
For i = 0 To groupSize - 1
    temp(i) = start + i
Next i
getElements = temp
End Function