Excel - How to count the number of sign changes (from + to - or vice versa) in a column?
Suppose you have a column of numbers and the data can be positive or negative. How do you count the number of times the data changes from positive to negative, or vice versa?
We will use three functions, SIGN, INT and SUM to solve the problem.
First we add a helper column B, name it "sign", then use SIGN function to get its sign. If the data is positive, it returns 1. If the value is negative, it returns -1. The formula is like:
=SIGN(A2)
Then we add another helper column C, call it "sign change", which checks whether sign of the current value is different from the last value. INT function is used to return the logical value TRUE or FALSE into 1 or 0.
At last, at the end of column C, we use a SUM function to sum all the value changes. In this example, the data sign changes for 4 times (-1 to -3, -3 to 4, 2 to -5, and -5 to 6).
VBA method
Below is the VBA code to achieve it. You need to add a clickable button on the spreadsheet and assign the following code to it.
Private Sub CommandButton1_Click()
Dim total_change As Integer
total_change = 0
Dim sign As String
Dim last_sign As String
Dim row As Integer
last_sign = "positive"
If Cells(2, 1) < 0 Then
last_sign = "negative"
End If
For row = 3 To 7
sign = "positive"
If Cells(row, 1) < 0 Then
sign = "negative"
End If
If last_sign <> sign Then
total_change = total_change + 1
End If
last_sign = sign
Next
MsgBox ("total sign change=" & total_change)
End Sub
Comments
Post a Comment