0

I'm building a pretty complicated VBA workbook, and one of the issues on running much of the code is performance. I have a built in function that does, more or less, the following

Public Function zzz (xxx as String) as String
if xxx = "apple" then zzz = "orange"
if xxx = "appple2" then zzz = "orange2"
if xxx = "apple3" then zzz = "apple3"

etc. (but with about 30 strings instead). I call this function multiple times. Is there a better way to do this?

3
  • You would be better off using vlookup() for this. Commented Jun 20, 2013 at 20:30
  • 2
    you could use if else at the least. Commented Jun 20, 2013 at 20:38
  • Is this a real example of what lookup value and result value would be? Commented Jun 20, 2013 at 20:39

3 Answers 3

2

You could make your function using combination of arrays and WorksheetFunction.Match. This would go this way:

Public Function zzz(xxx As String) As String
    Dim funInput As Variant
    Dim funOutput As Variant
        funInput = Array("apple", "apple2", "apple3")   
        'above array- add additional input elements and...
        '...match them with resulting items in below array
        funOutput = Array("orange", "orange2", "apple3") '

    zzz = funOutput(Application.Match(xxx, funInput, 0) - 1)
End Function

Sample call of the function in VBA:

Debug.Print zzz("apple2")

will result with:

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

1 Comment

+1 Haven't seen that approach before of using Application.Match to index an array. Innovative. Like it.
1

Hardly. And for 30 strings, this shouldn't be terribly slow.

The performance issues are likely to be in another place, especially where you interact with the workbook directly. Try to measure times of various procedures before randomly trying to update pieces of code.

A lot of lines doesn't mean slow performance. Not every line takes the same amount of time to execute.

Comments

1

You could try using Select Case, if you are only checking the value of one variable. That will be faster, because it will skip the remaining lines once it finds the correct variable.

Select case xxx
case "apple"
zzz = "orange"
case "apple2"
zzz = "orange2"
case "apple3"
zzz = "orange3"
End Select

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.