Link to home
Start Free TrialLog in
Avatar of Jeff9687
Jeff9687

asked on

SendKeys in mex file

Hey-- I have an Excel workbook containing macros that needs to be opened and run automatically with a Matlab EXE file. I have the VBA macros in an Auto_Open sub so that they are run immediately upon the opening of the workbook, and I've written Matlab code that automatically opens the Excel workbook. The problem is, when Excel opens, the "Enable or Disable Macros" prompt pops up, and it has to be clicked out of manually in order for the workbook to be opened and the macros to automatically run. The normal way around this is apparently to set the Macro Security level to "Low" which results in the workbook automatically being open with the macros enabled, but due to security settings on my computer I am unable to change the Macro Security level to anything lower than Medium.
 
In order to programmatically get past the prompt with macros enabled, it occurred to me that all that one would theoretically have to do is press "Tab" to select the "Enable Macros" button, and then "Enter" to get past the prompt, and that this could programmatically be done with the Matlab analog of the VBA "Sendkeys" function. After researching this, I can't find anything in Matlab that replicates the functionality of SendKeys, but it looks like it's actually possible to do in either C or C++, which can then be written into a mex file and executed in Matlab. I'm not really understanding how Sendkeys works in C/C++, though... is it possible to have C/C++ automatically press Tab,Enter in a mex file?

 Any help will be greatly appreciated!!
ASKER CERTIFIED SOLUTION
Avatar of exx1976
exx1976
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jeff9687
Jeff9687

ASKER

Hmm... OK well just using VB sendkeys (which I already know how to do) would certainly be easier than figuring out how to do it in C and then using a mex file to execute it in Matlab, but how do you call a VBS file from Matlab??
nevermind, i figured it out:

set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Sleep 100
WshShell.AppActivate "Microsoft Excel"
WScript.Sleep 1000
WshShell.SendKeys "{TAB}"
WScript.Sleep 1000
WshShell.SendKeys "{ENTER}"

Save in notepad as enablemacros.vbs, then in Matlab, call:
system('cscript enablemacros.vbs')

thanks for suggesting doing it in vbs!