How to execute a specific macro based on a variable?

I want to execute a specific macro based on a variable.

For example if the variable VarName is equal to A23, I want to execute Macro A23
If it is A67, I want to execute macro A67 etc.

OK, it looks like I can do it via Apple script, correct?

tell application "Keyboard Maestro Engine"
set MacroToRun to getvariable "VarName"
do script MacroToRun
end tell

That'll work.

Be aware that:

  1. If you want to use a local variable you'll need to modify the getvariable statement a bit (see the KM wiki on using variables in scripts)
  2. If the macro takes a long time to run the AppleScript might time out, so you might want to increase the default timeout period.

Here's the AppleScript code I use in a plugin action which you can adapt if you wish:

tell application "System Events"
	with timeout of 36000 seconds
		set _Macro to system attribute "KMPARAM_Macro" as text
		
		tell application "Keyboard Maestro Engine"
			with timeout of 36000 seconds
				do script _Macro
			end timeout
		end tell
	end timeout
end tell

and here's the plugin to download if you want:

TFL Execute a Macro.zip (443.7 KB)

1 Like