Hi Erica, this question involves writing a conditional test within a VBA function. I'll assume that you know how to build a function within a Visual Basic module in Excel, so I'll focus on just the code syntax here. There are usually multiple ways to approach a coding solution, and I'll outline two methods below. Overall, though, there are three basic steps to this function:
- Declare the Recommendation function as an Integer with two inputs, which you could call CurrentPrice and Projection. Both of the inputs should be Integers as well.
- Calculate the intended value of 1, -1, or 0. See details below.
- Close the function.
Following are two ways to handle the calculation for step 2:
Method 1: If/Else syntax. Since the formula can generate three potential values (1, -1, and 0), you'll need a sequence of If Then, ElseIf Then, and Else before closing with End If. Each test will compare the Projection and CurrentPrice inputs.
Method 2: Case syntax. This approach is a little more complex because you'll need to first Define a variable that contains the difference between Projection and CurrentPrice (a simple subtraction). You can then use this variable in a Case statement, with Case Is for 1, Case Is for -1, and Case Else for 0, before closing the statement with End Select.
For both methods, be sure to type the code using standard format practices, putting code on separate lines as needed. For example,
If Projection > (CurrentPrice + 10) Then
Recommendation = 1
Note, when you test this function in a spreadsheet, be sure to set CurrentPrice as an absolute cell reference (with dollar signs), not a relative cell reference, if you've put CurrentPrice into a single cell.
Hope this helps! Let me know if you have any questions on this.
Bill