将元素插入数组

时间:2020-03-08 13:34:59

标签: excel vba

我在Excel中有一个多维数组:

array in excel sheet

在VBA脚本中,我有以下代码:

Dim actualWeights
actualWeights = Range("A7:E21").Value

经过一些计算,我想在数组中添加丢失的ID。因此,在这种情况下,ID为3、4、6等。对不起,没有附加或插入功能。最好的方法是什么?

已添加: 因此,经过一些计算,我想插入到位:

<id: 3, weight: 34,92, measured: false, dailyLoss: 0,31, prediction: 0,00>

然后我要插入到位:

<id: 4, weight: 34,60, measured: false, dailyLoss: 0,31, prediction: 0,00>

等等直到所有缺少的ID都填满为止。在此示例中,id应该为1到24。

2 个答案:

答案 0 :(得分:3)

您可以像在不使用VBA的工作表中那样完全地在VBA中添加数据。

手动地,您将从第22行开始添加丢失的记录,并按 ID对表进行排序。 (这会将新记录上移到所需位置)

使用VBA,通过以下方式输入数据:

actualWeights = Range("A7:E100").Value

然后插入丢失的数据,最后使用VBA对最终产品进行排序。

答案 1 :(得分:1)

插入数组行

只是为了好玩,并演示使用Application.Index()函数将新项目行插入到现有数组中:

靠近OP的示例呼叫


Sub myData()
' Site: https://stackoverflow.com/questions/60588030/inserting-elements-into-an-array
    '[0] get original data
    Dim actualWeights
    actualWeights = MySheet.Range("A7:E21").Value             ' << change to actual sheet's CodeName

    '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    '[1] define data to be inserted
    '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Dim tobeInserted

    '<id: 3, weight: 34,92, measured: false, dailyLoss: 0,31, prediction: 0,00>
    tobeInserted = Array(3, 34.92, False, 0.31, 0)
    ins actualWeights, tobeInserted

    '<id: 4, weight: 34,60, measured: false, dailyLoss: 0,31, prediction: 0,00>
    tobeInserted = Array(4, 34.6, False, 0.31, 0)
    ins actualWeights, tobeInserted

    '[2] optional display at any range offset
    MySheet.Range("A7").Resize(UBound(actualWeights), 5).Offset(0, 6).Value = actualWeights

End Sub

程序调用{​​{1}}

ins()
相关问题