VBA Piecewise Functions

asdasd

New Member
Joined
May 11, 2011
Messages
3
Hi, I'm fairly new to this, I'm doing an assessment and I'm having a bit of trouble grasping how to do piecewise functions on VBA. I'm using BLOCK IFs to do this.

Heres my work so far:

x = [A2].Value

If (x <= 0) And (x < 90) Then
fx = Sin(x)
ElseIf (x >= 90) And (x < 180) Then
fx = -4 * Cos(x)
ElseIf (x <= 180) And (x < 270) Then
fx = SQRT((Sin(x) + 2) ^ 2 + 1)
ElseIf (x <= 270) And (x < 360) Then
fx = SIN( x )/2)*SQRT((SIN( x )+5)
End If

[B2].Value = fx

End Sub

It just wont seem to work when I try it, and I think it's to do with the SIN and COS etc in it, just I'm not sure. If anyone can help me out I'd be so grateful! Also I do know that I should be using radians, but at the moment I'm just trying to get it work and I'll deal with that sort of stuff afterwards.

Thanks again!
 

Excel Facts

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
Hi
Welcome to the board

I think some of the comparisons are wrong?

Code:
If [COLOR=red](x >= 0)[/COLOR] And (x < 90) Then
    fx = Sin(x)
ElseIf (x >= 90) And (x < 180) Then
    fx = -4 * Cos(x)
ElseIf [COLOR=red](x >= 180)[/COLOR] And (x < 270) Then
    fx = SQRT((Sin(x) + 2) ^ 2 + 1)
ElseIf [COLOR=red](x >= 270)[/COLOR] And (x < 360) Then
    fx = SIN( x )/(2*SQRT(SIN( x )+5))
End If

Please confirm
 
Upvote 0

Forum statistics

Threads
1,224,519
Messages
6,179,263
Members
452,902
Latest member
Knuddeluff

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top