PDA

View Full Version : [SOLVED:] VBA IF Function for Digital Flip Flop



DMain
01-14-2015, 02:44 AM
Hello,

I am trying to create a digital flip flop in VBA in order to test some data. The basics of the function are that it has 2 inputs, set and reset, and an output Q as follows in the Table bellow.


Input S

Input R

Output Q



1

1

1



1

0
1



0
1

0


0
0
Q(previous)




The function will only ever use binary values, 1 or 0. My code is basically 4 ifelse statements - for example if s and r = 1 then q = 1. My issue occurs when both the input S and R are zero. The output of the function should do nothing, i.e. hold the previous value however in my code the answer always defaults to zero. I am very new to VBA so any help would be appreciated. My code is as follows;

Function FLIP_FLOP(S, R) As Double
If S = 0 And R = 0 Then
Exit Function
ElseIf S = 0 And R = 1 Then
FLIP_FLOP = 0
ElseIf S = 1 And R = 0 Then
FLIP_FLOP = 1
ElseIf S = 1 And R = 1 Then
FLIP_FLOP = 1
ElseIf S = 0 And R = 0 Then
End If
End Function

Thanks for any help,
DMain

Bob Phillips
01-14-2015, 02:56 AM
The problem is that you cannot have a value in Q and then overwrite it with a formula hoping that in some circumstances the value in Q is retained. You either have the formula or have a value. And the formula knows nothing about what was there.

the best way would be to have a change event within that worksheet code module that does it


Private Sub Worksheet_Change(ByVal Target As Range)

On Error GoTo ws_exit

Application.EnableEvents = False

With Target

If .Column = 18 Or .Column = 19 Then

Select Case True

Case Me.Cells(.Row, "R").Value = 0 And Me.Cells(.Row, "S").Value = 0

'do nothing

Case Me.Cells(.Row, "R").Value = 1 And Me.Cells(.Row, "S").Value = 0

Me.Cells(.Row, "Q").Value = 0

Case Me.Cells(.Row, "R").Value = 0 And Me.Cells(.Row, "S").Value = 1

Me.Cells(.Row, "Q").Value = 1

Case Me.Cells(.Row, "R").Value = 1 And Me.Cells(.Row, "S").Value = 1

Me.Cells(.Row, "Q").Value = 1
End Select
End If
End With

ws_exit:
Application.EnableEvents = True
End Sub

ValerieT
01-14-2015, 02:59 AM
full code?



if S+R=0
'(do nothing to keep previous value if this is what you want, not sure I understood)
else
if S= 1 'in your example, S is enough to decide the output
flip_flop=1
else
flip_flop=0
endif
endif

SamT
01-15-2015, 12:06 AM
Function FLIP_FLOP(S, R) As Double
Static Q As Integer

If S + R = 0 Then
Q = Q
Else
Q = S
End If
FLIP_FLOP = Q
End Function

DMain
01-15-2015, 01:13 AM
Thanks for everyone's help. The solution SamT proposed works and is the one I will use. Thanks SamT!