How to run a macro only if the Excel workbook is o

2019-05-23 15:34发布

World!

I am trying to automate a report task at my job and I have the following situation:

I need to execute a macro on a workbook by using a script. I tried to write a vbscript to do the job, and this is the significant part of it:

Set objWbk = GetObject("***Path***\test.xlsm")

objWbk.Application.Run "test.xlsm!test" 

WScript.Quit

The macro runs perfectly. My real problem is that I only want to do the report only if the workbook is open.

Is there a way (in vbs or vba) to determine if that workbook is open ? (by the way, it is located on another computer on my network)

2条回答
祖国的老花朵
2楼-- · 2019-05-23 15:48

Since you want to run the macro only when the workbook is already opened, something like this might work:

wbName = "test.xlsm"
wbFullName = "***Path***\" & wbName

Set xl = GetObject(, "Excel.Application")
For Each wb In xl.Workbooks
  If LCase(wb.Path & "\" & wb.Name) = wbFullName Then
    wb.Application.Run wbName & "!test"
  End If
Next
查看更多
放荡不羁爱自由
3楼-- · 2019-05-23 16:11

This is not fully tested and may a need a bit of modification but see if it gets you what you need.

On Error Resume Next
Set objWbk = GetObject("***Path***\test.xlsm")

If Err.Number = 0 Then objWbk.Application.Run "test.xlsm!test" 

wScript.Quit
查看更多
登录 后发表回答