Is it possible to run macro only when excel file i

2019-09-17 02:39发布

I have scheduled a file to open, run macro and close after that. Everything works fine, except if I want to open the file manually, it closes on opening as it runs the macro. Is it possible to set macro to run only when file is opened automatically?

3条回答
我只想做你的唯一
2楼-- · 2019-09-17 03:14

Sounds like your Sub is using the Open Event. Just have it as a regualr Sub, inside a module, and use your vbs script to open the worksheet and run the macro.

I used to do this all the time but can't find my old scripts. Found this and I know it's similar to my old ones.

Dim xlApp
Dim xlWkb
Set xlApp = CreateObject("excel.application")
Set xlWkb = xlApp.Workbooks.Open("PATH TO YOUR FILE")
xlApp.Visible = True
xlWkb.RunAutoMacros 1 'enables macros to be run on open
xlApp.Run ("YOUR PROCEDURE")
xlApp.Workbooks("YOUR WORKBOOK NAME").Save 'Save the workbook
xlApp.Quit 'quits excel

Save as .vbs and schedule. Example found here . This way you can open and edit your script any time you want without it auto running.

查看更多
做个烂人
3楼-- · 2019-09-17 03:21

If the time of the day you open the file yourself and the time of the day when scheduler opens it never overlap you can just add a check on current time before running the code, and if it is within the window of the scheduler to run the macro, other wise not to.

查看更多
爷、活的狠高调
4楼-- · 2019-09-17 03:37

Excel can't detect if it is opened manually or by scheduler. But if you open it manually you can open it in protected view and disable macros this way. In the 'Open..' dialog click the small arrow on the 'Open' button and then select 'protected view'.

查看更多
登录 后发表回答