'Loop through cells and place specific values onto them [duplicate]

So I want to create a table like this

enter image description here

I want those specific numbers on the cells.

I had an idea of how to do it where I check the value of the cell above the one I'm filling in.

Something like this

if cell_above.value = 2 then
current_cell.value = -2

if cell_above.value = -2 then
current_cell.value = 4

and on and on like that.

This just seems like a lot of work and there is probably an easier way to do this. Can somebody help me think of another way to solve this? Thank you



Solution 1:[1]

Still not clear what your problem is. Define a const Array of values and write them to the sheet. Following three variations to get you the idea:

Sub fillMe1()
    Dim MyValues
    MyValues = Array(2, -2, 4, -4, 6, -6, 3, -3, 5, -5, 7, -7)
    With ThisWorkbook.Sheets(1)
        .Range("A1").Resize(UBound(MyValues) + 1, 1).Value = Application.Transpose(MyValues)
    End With
End Sub

Sub fillMe2()
    Dim MyValues
    MyValues = Array(2, -2, 4, -4, 6, -6, 3, -3, 5, -5, 7, -7)
    Dim i As Long
    
    For i = 0 To UBound(MyValues)
        With ThisWorkbook.Sheets(1)
            .Range("B1").Offset(i, 0).Value = MyValues(i)
        End With
    Next i
End Sub

Sub fillMe3()
    Dim MyValues
    MyValues = Array(2, 4, 6, 3, 5, 7)
    Dim i As Long
    
    For i = 0 To UBound(MyValues)
        With ThisWorkbook.Sheets(1)
            .Range("C1").Offset(i * 2, 0).Value = MyValues(i)
            .Range("C1").Offset(i * 2 + 1, 0).Value = MyValues(i) * -1
        End With
    Next i
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FunThomas