2

Okay, I feel like I'm missing something major here; however I am trying to subtract arrays on VBA. I need to subtract the arrays and assign them to another variable x so I cant do a normalizing function. Below is my version of the code:

Code:

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

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

x = xTable - xnew

MsgBox (x)

I swear this is a stupid question and I have looked around the internet for this simple operation, but to my demise, nothing has come up... I see this question as different to MINUS operation on Array elements because the person asking here is trying to change the size of the array, I am not.

JakeK
  • 76
  • 2
  • 18
  • Check the answers in this thread [MINUS operation on Array elements](https://stackoverflow.com/questions/13931786/minus-operation-on-array-elements). Looks like you will need named ranges or a loop. Does not seem like "array subtraction" is supported in vba. – Jacob H Jun 14 '18 at 19:59

2 Answers2

3

You can also use strings and Application.Evaluate to avoid the loop:

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
Scott Craner
  • 148,073
  • 10
  • 49
  • 81
1

I think you're trying to subtract them as a matrix. VBA isn't that smart. You need to loop through the array and do the subtraction yourself.

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

Output

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

Note: If you don't know the size of the xTable then you can do ReDim x(LBound(xTable) To UBound(xTable) to set the correct dimensions on x

Drew Chapin
  • 7,779
  • 5
  • 58
  • 84