Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

alternative way for triggering event procedures from EXCEL VBA User Defined Functions #10

Open
testor2897 opened this issue Jan 27, 2023 · 0 comments

Comments

@testor2897
Copy link

testor2897 commented Jan 27, 2023

Hi,
sorry for using issues as I found no other direct contact possibility.
I read the article with a lot of interest (https://rubberduckvba.wordpress.com/2021/03/19/globals-and-ambient-context/), Thanks a lot.
There is an alternative way for triggering event procedures from Excel VBA User Defined Functions (relating to your article).

  1. You start a seldom used key event procedure in Sub Auto_Open and declare a global variable (for triggering) like:
' variable to store the Application.Caller.Address (inkl. Workbook and Worksheet)
Public actKeyAddress$

Sub Auto_Open()
  actKeyAddress = ""
  Application.OnKey "^{F15}", "ColorCell"
End Sub

  1. You define a procedure to do something asynchron (in this case reformat the Application.Caller cell):
  Sub ColorCell()
  If actKeyAddress = "" Then Exit Sub
  
  On Error Goto FinalEnd
  With Range(actKeyAddress)
    .ClearFormats
    .HorizontalAlignment = xlCenter
  With .Interior
    .Pattern = xlPatternRectangularGradient
    .Gradient.RectangleLeft = 0.5
    .Gradient.RectangleRight = 0.5
    .Gradient.RectangleTop = 0.5
    .Gradient.RectangleBottom = 0.5
    .Gradient.ColorStops.Clear
  End With
  With .Interior.Gradient.ColorStops.Add(0)
    .Color = 6750207
  End With
  With .Interior.Gradient.ColorStops.Add(1)
    .ThemeColor = xlThemeColorDark1
  End With
  End With
  With Range(actKeyAddress).Font
    .Name = "Webdings"
    .Size = 12
    .Bold = True
    .Color = -65536
  End With

FinalEnd:
  ' important: reset triggering variable!
  actKeyAddress = ""
End Sub
  1. You fire the event from within an UDF:
 Function myFunction( ... ) 
  Dim actWorkbook$
  Dim actWorksheet$
  Dim actCell$
...
  With Application.Caller
    actCell = .Address
    actWorksheet = .Parent.Name
    actWorkbook = .Parent.Parent.Name
  End With

  actKeyAddress = "[" & actWorkbook & "]" & actWorksheet & "!" & actCell
  SendKeys "^{F15}"
  ...
End Function

Greetings,

Sebastian

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant