How to pass KM Variable into a Word Mac 2011 Macro (as a Variable)?

Actually, you didn't set nor create a VBA Doc variable.
My code does both. ha ha ha :sunglasses:

Yes, and I'm working off of your code. :smile:

OK, showoff, why don't you show the OP how to get the KM var in AppleScript? :wink:

[quote=“JMichaelTX, post:9, topic:2582”]But mine works, and it runs fast.So does it really matter?/quote]

Hey JM,

Suppose you have 50 variables? Do you really want to try to manage them by position or otherwise piecemeal?

tell application "Microsoft Word"
  tell active document
    name of variables
  end tell
end tell

It’s a whole lot easier to work with variables by name:

tell application "Microsoft Word"
  tell active document
    if not (variable "KMVar1" exists) then
      make new variable at it with properties {name:"KMVar1", variable value:"Set by AppleScript"}
    else
      set myVarName to variable value of variable "KMVar1"
    end if
  end tell
end tell

-Chris

Actually I wasn't doing that.

I have two lines of code:

set lstVar to variables of active document whose name is strVarName
set oVar to first item in lstVar -- Get the Record out of the List

for your one line:

tell active document to set oVar to variable strVarName

My first line gets ONLY the desired variable by name, but it is in a list, whereas yours gets the variable directly.
Getting the "first item" is get the one and only item in that list.

Not that much different, IMO.

####IAC, here's my code updated with your approach, FWIW:
I left my code there for visibility, just commented it out.

####EDIT: Wed, Dec 16, 2015 at 6:33 PM
I have removed my code because it fails due to a bug in the Word AppleScript interface.

See my corrected/final code below at:

Hey JM,

This is actually new and improved in KM 7.0.2. (REQUIRES Keyboard Maestro 7.0.2)

####Set Keyboard Maestro variable using AppleScript.

---------------------------------------------------------------------
# Keyboard Maestro — Set value of variable "<variable name>"
---------------------------------------------------------------------
set myText to "whatever"

tell application "Keyboard Maestro Engine"
  if variable "myKMVariableName" exists then
    set value of variable "myKMVariableName" to myText
  else
    make new variable with properties {name:"myKMVariableName", value:myText}
  end if
end tell
---------------------------------------------------------------------

####Get Keyboard Maestro variable using AppleScript.

---------------------------------------------------------------------
# Keyboard Maestro — Get value of variable "<variable name>"
---------------------------------------------------------------------
tell application "Keyboard Maestro Engine"
  if variable "myKMVariableName" exists then
    set myAppleScriptVariableName to value of variable "myKMVariableName"
  end if
end tell
---------------------------------------------------------------------

-Chris

1 Like

Great! Thanks.

May I suggest that you put this in the KM Wiki?

Hey JM,

Oops. Missed that.

Still you're not going to have more than one variable with the same name, so why not save a step.

One way your approach might become more relevant is if you need to list more than one variable with similar names:

tell application "Microsoft Word"
  tell active document
    variables whose name contains "KM"
  end tell
end tell

OR

tell application "Microsoft Word"
  tell active document
    tell (variables whose name contains "KM")
      set varNameList to name
      set varValueList to variable value
    end tell
  end tell
end tell

-Chris

2 Likes

I agree. My only point is that my code wasn't really that different.
But no need to use two statements when one will do.

And your approach is very clear:
tell active document to set oVar to variable strVarName

It's very readable and obvious what that is doing.

Microsoft could haved save me, and I'm betting many others, a lot of work and time if they would have included some simple examples in their AppleScript Dictionary.

But, I learned a lot today, and that's always a good thing. :+1:

Chris, did you test this?

I'm finding that it always returns true, even when the variable does not exist.

My test code:

tell active document
	if (variable strVarName exists) then
		display dialog strVarName & " EXISTS"
	else
		display dialog strVarName & " Does NOT exist"
	end if
end tell

Hey JM,

Wow, that's nasty. I'll get back to you in a bit.

-Chris

Hey JM,

Bleck. Run this.

set strVarName to "sackOfSnot!"
tell application "Microsoft Word"
  tell active document
    set tempVar to variable strVarName
    properties of tempVar
  end tell
end tell

Bad behavior…

-Chris

It exists, it's just missing. LOL

So I guess we have to check for "missing value"

This works:

tell application "Microsoft Word"
	set strVarName to "KMVar-Test1" -- VBA Document Variable that corresponds to KM Variable
	
	tell active document
		if (name of (variable strVarName) is missing value) then
			display dialog strVarName & " MISSING"
		else
			display dialog strVarName & " FOUND"
		end if
	end tell
end tell

We've had great discussion, and I've learned a lot.

###Attached is the final macro that does it all:

[VBA] How to Set VBA Variable.scpt.zip (12.5 KB

Script is too long to post, so I'm just attaching a zip file, and posting the header comments. My thanks to @ccstone for his help as seen in this thread.

This script is just and example. it is NOT bullet-proof, and certainly needs more testing and error trapping before you use it in a production environment.

I have done some limited end-to-end testing, and it seems to work OK.

If you, or anyone, finds any issues, or has suggestions for improvement, please post here.

(*
====================================================
	How to Set Word VBA Document Variable with AppleScript
====================================================

DATE:   Tue, Dec 15, 2015
AUTHOR: JMichaelTX

PURPOSE:
	• Run Word VBA Macro using Data from KM Variable(s)
	
PROCESS:  This script performs the following steps:
	1. Prompts User for VBA Macro Name
	2. Prompts User for Word doc file to open
	3. Prompts User for KM Variable to use
	4. Opens the Word file
	5. Gets the KM variable value
	6. Sets (and creates if necessary) the Word Document Variable to the KM Variable value
	7. Runs the VBA macro
	
CHANGES NEEDED:
	• Move the code to create/set the Word doc variable into a function
	• Add another Word variable that is the name of the KM var being set
	• Revise the Word Macro to use this variable.
	
REF:    KM Forum Topic
	How to pass KM Variable into a Word Mac 2011 Macro (as a Variable)?
	https://forum.keyboardmaestro.com/t/how-to-pass-km-variable-into-a-word-mac-2011-macro-as-a-variable/2582
====================================================
*)
1 Like

I'm having another look at this.
My needs are a lot "simpler" so I have removed lots of the extra coding checks.

— I have 1 KM Variable called bb_PlaceName that always exists.
— My DOCX is open and the same named var (bb_PlaceName) exists and is DIM'd inside a (known) Word Macro that I will initiate.
— I hope to include the core code from the Word Macro below inside my own Word macro to “pass the KM Var’s value and use it inside of my Word Macro"
— I want to "start" this process from my KM Macro. That would presumably run the Applescript followed by opening my Word Doc and initiating my Word Macro.

I am hitting an Applescript error as follows. Any ideas?
Also, does the other code look OK? Thanks.

The code (and error message) is in the screenshot and also here as text (can you remind me how to embed this as code into this forum?):

set strVarName to "bb_PlaceName" -- Name of both KM variable and Word Variable

set strVarValue to getKMVar(strVarName) -- Get value of KM var

tell application "Microsoft Word"
  tell active document
    set variable value of strVarName to strVarValue
  end tell
end tell

--———————————————————————————————
on getKMVar(pstrVarName)
  
  tell application "Keyboard Maestro Engine"
    set strKMVarValue to value of variable pstrVarName
    return strKMVarValue
  end tell -- "Keyboard Maestro Engine"
  
end getKMVar
--———————————————————————————————

(*
=============== WORD VBA MACRO ===========
Sub TEST_KM_Var()

MsgBox ActiveDocument.Variables(bb_PlaceName).Value

End Sub
=======================================
*)

Here is a MS Word 2011 VBA macro that will get the KM Variable directly from KM, without needing an external AppleScript. I uses the VBA MacScript( ) function to run an AppleScript that gets the KM Var.

NOTE: This may NOT work in Word 2016. I don't know. I don't have Word 2016, therefore I have NOT tested it there.

Good luck, and let us know how it goes.

There are two macros below:

  1. A Sub to test the function
  2. The Function that actually gets the KM Var

It has some error handling, but you should use with caution until you have thoroughly checked it out.

Sub TEST_KMVar()

Dim KMVarName As String
Dim KMVarValue As String

KMVarName = "YOUR KM Var Name Here"

On Error GoTo err_Error_handler

KMVarValue = getKMVar(KMVarName)
Debug.Print KMVarValue

MsgBox "Variable: " & KMVarName & vbCr & "Value: " & KMVarValue, vbOKOnly, "Get Keyboard Maestro Variable"

Exit Sub

err_Error_handler:
    MsgBox "Sub Cancelled due to error"
    
End Sub


    
    
Function getKMVar(pKMVarName As String) As String

    '================================================================
    ' VBA Function:     getKMVar(pKMVarName As String)
    '
    '   VER:  1.0       DATE:   2016-03-19
    '
    '   PURPOSE:  Get the Value of a KM Variable from a VBA Macro
    '
    '   AUTHOR:
    '       JMichaelTX
    '
    '  REQUIRES:
    '       1.  MS Office 2011 Mac (may NOT work with later versions of Office)
    '       2.  Keyboard Maestro 7.0.3+
    '       3.  Mac OS X Yosemite (10.10.3)+
    '
    '=================================================================
    '


Dim resultsStr As String
Dim scriptStr As String
Dim errorStr As String

scriptStr = "tell application ""Keyboard Maestro Engine"" to get value of variable """ & pKMVarName & """"
Debug.Print scriptStr

On Error Resume Next

resultsStr = MacScript(scriptStr)

If Err = 5 Then
    errorStr = "***ERROR*** " & vbCr & "KM Variable was NOT found: " & pKMVarName
    getKMVar = errorStr
    MsgBox errorStr & vbCr & "SCRIPT:" & vbCr & scriptStr
    On Error GoTo 0
    Err.Raise 5000, "getKMVar", "KM Var NOT Found"
    
    Exit Function
    
End If

getKMVar = resultsStr

End Function
1 Like

I will take look at the new code.

Can you see what is wrong with the code I included in my message below? Thanks.

Sorry, I don't have time now. Why don't you see first if you can make use of the code I just provided. It should allow you to greatly simplify your process.

Hey Steve,

Look for “code block” on this page:

Using Markdown Formatting on the Forum

-Chris

1 Like

This code does work and seems to be a better way to do this. Thanks.