Skip to main content
5 of 8
corrected lang from vb to vba
Taylor Raine
  • 8.7k
  • 2
  • 27
  • 51

Simplify built-in functions

When using certain functions frequently, reassign them to a user-defined function.

The following code (127 chars) can be reduced from:

Sub q()
w = 0
x = 1
y = 2
z = 3
a = Format(w, "0.0%")
b = Format(x, "0.0%")
c = Format(y, "0.0%")
d = Format(z, "0.0%")
End Sub

to (124 chars):

Sub q()
w = 0
x = 1
y = 2
z = 3
a = f(w)
b = f(x)
c = f(y)
d = f(z)
End Sub
Function f(g)
f = Format(g, "0.0%")
End Function

Combining this with the ByRef trick, you can save even more characters (down to 114):

Sub q()
w = 0
x = 1
y = 2
z = 3
a = f(w)
b = f(x)
c = f(y)
d = f(z)
End Sub
Sub f(g)
g = Format(g, "0.0%")
End Sub

Do this judiciously, as VBA takes up a lot of characters to define a Function. The second code block would actually be larger than the first with any number fewer Format() calls.

Gaffi
  • 3.7k
  • 2
  • 23
  • 54