数组加法/减法vba

时间:2018-06-14 19:57:53

标签: vba math

好吧,我觉得我在这里缺少一些重要的东西;但是我试图在VBA上减去数组。我需要减去数组并将它们分配给另一个变量x,所以我不能做一个规范化函数。以下是我的代码版本:

代码:

Dim xnew As Variant, xTable As Variant, x As Variant

xnew = [{1,2}]
xTable = [{4,3}]

x = xTable - xnew

MsgBox (x)

我发誓这是一个愚蠢的问题,我在互联网上寻找这个简单的操作,但是对于我的死亡,没有任何事情发生......我认为这个问题与MINUS operation on Array elements不同,因为这个问题的人这里是试图改变数组的大小,我不是。

2 个答案:

答案 0 :(得分:2)

您还可以使用字符串和Application.Evaluate来避免循环:

Dim xnew As String, xTable As String, x As Variant

xnew = "{1,2}"
xTable = "{4,3}"

x = Application.Evaluate("INDEX(" & xTable & " - " & xnew & ",)")

For i = LBound(x) To UBound(x)
    Debug.Print "x(" & i & ") = " & x(i)
Next

答案 1 :(得分:1)

我认为你试图将它们减去矩阵。 VBA并不那么聪明。你需要遍历数组并自己进行减法。

Dim xnew As Variant, xTable As Variant, x(1 To 2) As Variant, i As Integer

xnew = [{1,2}]
xTable = [{4,3}]

For i = LBound(xTable) To UBound(xTable)
    x(i) = xTable(i) - xnew(i)
Next

For i = LBound(x) To UBound(x)
    Debug.Print "x(" & i & ") = " & x(i)
Next

<强>输出

  

x(1)= 3
  x(2)= 1

注意:如果您不知道xTable的大小,那么您可以ReDim x(LBound(xTable) To UBound(xTable)x上设置正确的尺寸