0

I want to convert this code into a function format. I've tried inputting function instead of sub version, but when I type =version into a cell nothing shows up. any help is appreciated

Sub Version()

    If Range("B2").Value = 20.2 Then
        Range("B22").Value = 20.3

    If Range("B2").Value = 20.3 Then
        Range("B22").Value = 20.1
    End If
    End If

End Sub
2
  • 1
    You can't (except in some edge cases) modify another cell on the worksheet using a UDF. Commented Feb 11, 2020 at 19:52
  • 1
    You need to add a return. So if the function is called version you need version = value. What you have now would need to be manually executed everytime and will only work for a single cell. Commented Feb 11, 2020 at 19:52

2 Answers 2

3

To use this function you need to write =Version(B2) on your cell B22:

Option Explicit
Function Version(Target As Range) As Single

    Select Case Target.Value
        Case 20.2
            Version = 20.3
        Case 20.3
            Version = 20.1
        '...
    End Select

End Function

Example:

Exmaple

Sign up to request clarification or add additional context in comments.

2 Comments

I've typed =Version(B2) into cell B22 and got an error. I've replaced my original code with the code above. any other suggestions? @JvdV
brb1011 it should work. I've just tried and it does. Check the answer, I've attached an image.
0

It's been a while since I've written VBA. Your subroutine suggests some weird, and so I suspect unintended logic. I suspect you mean that if the value is 20.2, return 20.3 and if it's 20.3, return 20.1.

As it's written, it will NEVER set B22 to 20.1 because B2 would have to be equal to both 20.2 and 20.3 because of the nested ifs.

What I offer is a function that takes a range as input (presumably cell B2) and returns a value. If the input is 20.2, you get 20.3. If it's 20.3, you get 20.1. Otherwise you get whatever was in B2. You could put the formula = customFunc(B2) in cell B22 to get the result.

Public Function customFunc(rngIn As Range)
    custFunc = rngIn.Value
    If rngIn.Value = 20.2 Then
        customFunc = 20.3
    End If
    If rngIn.Value = 20.3 Then
        customFunc = 20.1
    End If
End Function

1 Comment

RMacey you could use ElseIf instead another if so it doesn't evaluate always both ifs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.