简体   繁体   中英

Using VB script to run VBA Macros and save the excel workbook

I am trying to run a macro from a * .vbs file. You can find the code below. The module runs with no issue (this has been tested). But workbook is not saved. I tried adding ThisWorkbook.Save into the module itself but it causes an error and tells me that my file is ReadOnly . To clarify, I want to know how to save the workbook after running a macro through VBScript.

Option Explicit

'On Error Resume Next 'Comment-out for debugging

ExcelMacro

Sub ExcelMacro() 

 Dim xlApp 
 Dim xlBook 

 Set xlApp = CreateObject("Excel.Application") 
 Set xlBook = xlApp.Workbooks.Open("\\internal.company.com\River_Automated.xlsm", 0, True) 
 xlApp.Run "Update"

 xlBook.Save
 xlBook.Close
 xlApp.Quit 

 Set xlBook = Nothing 
 Set xlApp = Nothing 

End Sub 

Some side notes that may be helpful:

After running VBScript I got this message that:

Resume.xlsw already exists. Do you want to replace it?

I added lines that create a text file right before End Sub and it creates it. So, it runs the macro but does not save the workbook.

This line:

Set xlBook = xlApp.Workbooks.Open("\\internal.company.com\River_Automated.xlsm", 0, True) 

Is causing the file to be opened in ReadOnly mode. The third argument of the Open method determines whether to open the file in ReadOnly mode if True , or otherwise False .

ReadOnly | Optional | Variant | True to open the workbook in read-only mode.

The solution would be either to open the file in ReadOnly = False via:

Set xlBook = xlApp.Workbooks.Open("\\internal.company.com\River_Automated.xlsm", 0, False)

Or, to check if the file is ReadOnly and if so, save it as something else.

If Not xlBook.ReadOnly Then
    xlBook.Save

Else
    xlBook.SaveAs ... '### Modify as needed
End If
xlBook.Close
xlApp.Quit 

Set xlBook = Nothing 
Set xlApp = Nothing 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM