View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
JohnC[_3_] JohnC[_3_] is offline
external usenet poster
 
Posts: 2
Default How to make a VBA Function return a value in percent format

On Tuesday, October 2, 2012 5:17:28 PM UTC-4, John Black wrote:
Hi, I've been searching google for a while on this question but I can't find anything. I wrote a very simple function that returns the growth percentage between two numbers: Function GP(Val1 As Double, Val2 As Double) GP = (Val2 - Val1) / Val1 End Function I would like the result to automatically be displayed in "%0.00" format but I cannot figure out how to make that happen. Right now it returns a number like 0.45632 and I have to click the cell and format it to percentage. Is this possible? Thanks. John Black


Hi,

I'm pretty sure that what you are asking for is impossible in that VBA functions
when used as worksheet functions have no side-effects and changing cell format
would be a side effect. One idea that I tested (to some extent) and which seems to work is to add an event-handler which does the side effect when you want automatically whenever the formula is entered:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
On Error Resume Next
If UCase(Target.Formula) Like "=*GP(*" Then Target.NumberFormat = "0.00%"
End Sub

If you haven't done things like this before - this should be put
in the code for the Workbook object rather than in a general code module.
The On Error Resume Next was needed since if you e.g. highlight a range of cells
and hit delete then it triggers the Change event but with no well-defined
target.formula

This approach has a certain overhead of course. You can always remove the event-handler at a later time once you are happy with your workbook.

hth

-John