Home > database >  Printing the output of an if-then statement in another column
Printing the output of an if-then statement in another column

Time:11-18

This sounds like the most simple thing ever but here I am.

I have a column with positive and negative numbers. I'm trying to script a code that will print either "P" or "N" in column B (or C or D, doesn't matter) depending on the value of the cell.

For example, if cell A2 has the value -32, then cell B2 should be assigned the string "N". Then goes A3/B3, A4/B4, and so on.

My trouble isn't with the if-then-else stament per se, rather HOW I can get the output to be printed where I want it to be.

Sub Negatives()
value = Range("A:A")
    If Sgn(value) < 0 Then
        //??? N
    ElseIf Sgn(value) >= 0 Then
        //??? P
    End If
End Sub

Should I be using a for-loop instead to iterate through every value in the column?

CodePudding user response:

Short answer yes. You could construct an array and stamp it in all at once but that will still require a loop to make decisions on each cell value.

I'd suggest:

Sub Negatives()
    Dim numberRange As Range
    Set numberRange = ThisWorkbook.Sheets("Sheet1").UsedRange.Columns("A")
    
    For Each cell In numberRange.Cells
    
        If cell.Value < 0 Then
            cell.Offset(0, 1).Value = "N"
        ElseIf cell.Value >= 0 Then
            cell.Offset(0, 1).Value = "P"
        End If
    Next
    
End Sub
  • Related