VBA Splitting array difficulties

67 Views Asked by At

So I am trying to split an array into two halves and am having allot more trouble than I anticipated. Setting break points, I know that as these lines are being executed "sz"(Integer) is set to 9. This code sets "rightSz"(Integer) to be 4, which is what I expected, but it also sets "leftSz"(Integer) to be equal to 6. I have no idea why it is giving me this and it is causing a lot of problems in later sections of my code.

If sz Mod 2 = 1 Then
               rightSz = sz / 2
               leftSz = rightSz + 1
        Else
                leftSz = sz / 2
                rightSz = sz / 2
        End If
2

There are 2 best solutions below

0
On BEST ANSWER

Here is another approach, using the Int() function to round down half of the original number to a whole number. The other half is calculated by computing the difference from the original. Might be slightly less confusing if people are not as familiar with Mod.

Public Sub TestSplitArray()

    Dim sz As Integer
    Dim intPart1 As Integer
    Dim intPart2 As Integer

    sz = 9

    intPart1 = Int(sz / 2)
    intPart2 = sz - intPart1

    Debug.Print "sz=(" & intPart1 & "+" & intPart2 & ")"

End Sub

Also note that / is not the same as \ when it comes to division in VBA. The forward slash returns the fraction, while the backslash returns a whole number. Using this concept, you could use the backslash instead of the Int() function to yield the same result.

Public Sub TestSplitArray()

    Dim sz As Integer
    Dim intPart1 As Integer
    Dim intPart2 As Integer

    sz = 9

    intPart1 = sz \ 2
    intPart2 = sz - intPart1

    Debug.Print "sz=(" & intPart1 & "+" & intPart2 & ")"

End Sub
0
On

The code seems right, it could be an issue with the dimensioning of the variables

This one makes leftSz == 5 and rightsz == 4

Sub test()
    Dim sz As Long, leftsz As Long, rightsz As Long
    sz = 9

    If sz Mod 2 = 1 Then
           rightsz = sz / 2
           leftsz = rightsz + 1
    Else
            leftsz = sz / 2
            rightsz = sz / 2
    End If
End Sub