Home > OS >  Is there a way to use a variable as a function?
Is there a way to use a variable as a function?

Time:08-30

I want to replace a lot of things in a string, but i dont want to write "Replace" everytime

Sub test()
Let b = "replace"
Let a = "abc"
Debug.Print Evaluate(b(b(a, "a", "b"), "b", "d"))
End Sub

Is there a way to set "b" to be evaluated like a function? Or assign a function to a variable and then use it?

I know i can use this

Sub test()
Let b = "replace"
Let a = "abc"
With WorksheetFunction
  x = .Substitute(.Substitute(a, "a", "b"), "b", "d")
Debug.Print x
End Sub

But would be the same thing, write "Substitute" all time

The actual code is bigger than this, this is just an example

CodePudding user response:

For the case of Replace, I suggest just writing a new function:

Function b( _
    ByRef Expression As String, _
    ByRef Find As String, _
    ByRef Replace As String _
) As String
    
    b = VBA.Replace(Expression, Find, Replace)
End Function


Sub test()
    Dim a As String
    a = "abc"
    
    Debug.Print b(b(a, "a", "b"), "b", "d")
End Sub

However...

I want to replace a lot of things in a string, but i dont want to write "Replace" everytime.

Seems like an XY problem. Use two arrays and a loop:

Sub test2()
    Dim oldLetters As Variant
    oldLetters = Array("a", "b")
    
    Dim newLetters As Variant
    newLetters = Array("b", "d")
    
    Dim a As String
    a = "abc"
    
    Dim i As Long
    For i = LBound(oldLetters) To UBound(oldLetters)
        a = Replace(a, oldLetters(i), newLetters(i))
    Next
    
    Debug.Print a
End Sub
  • Related