I have a VBScript that opens all the excel files in a folder one by one and copies a certain range into a summary file. The summary file stays open through the entire operation, but the other files are closed after copying the range. This means that the Excel application stays open the whole time.
The problem is that Windows is holding onto each workbook even after it closes and the memory use steadily climbs. I tried to isolate the problem by disabling all add-ins and removing the personal.xlsb worksheet. I then manually opened several workbooks (no script involved) and closed them one by one. The memory use increased with each open file but did not decrease when I started closing them.
I have searched for hours now and the only answer I can find is to quit and restart the application. That's a pathetic workaround (and a pain for my script) - there has to be a better way to release closed workbook memory.
I'm running Excel 2013.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Shell.Application")
'Get summary folder location
Set StartFolder = objShell.BrowseForFolder(0, "Select the folder to summarize", 0, 5)
If StartFolder Is Nothing Then
Wscript.Quit
End If
StartFolderName = StartFolder.self.path
Set SuperFolder = objFSO.GetFolder(StartFolderName)
'Open Excel
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
Set objWorkbook = objExcel.Workbooks.Add()
NewExcelName = StartFolderName & "\Summary.xlsx"
objWorkbook.SaveAs(NewExcelName)
Call ShowSubfolders (SuperFolder)
'------------------------------------------------------------------------------
'Save and quit
objWorkbook.Save
objExcel.Quit
Wscript.echo "Done"
'------------------------------------------------------------------------------
Sub ShowSubFolders(fFolder)
Set objFolder = objFSO.GetFolder(fFolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
'Open document
Set objxls = objExcel.Workbooks.Open(objFile.path)
'Do stuff here
'Close Document
objxls.Close False
Next
For Each Subfolder in fFolder.SubFolders
ShowSubFolders(Subfolder)
Next
End Sub
Try objxls.quit
The Set objxls = Nothing just destroys the object reference. The .quit method destroys the object itself.
Related
I'm trying to run an Excel macro from outside of the Excel file. I'm currently using a ".vbs" file run from the command line, but it keeps telling me the macro can't be found. Here is the script I'm trying to use
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("test.xls")
objExcel.Application.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"
objExcel.Application.Run "Macro.TestMacro()"
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
And here is the Macro I'm trying to access:
Sub TestMacro()
'first set a string which contains the path to the file you want to create.
'this example creates one and stores it in the root directory
MyFile = "C:\Users\username\Desktop\" & "TestResult.txt"
'set and open file for output
fnum = FreeFile()
Open MyFile For Output As fnum
'write project info and then a blank line. Note the comma is required
Write #fnum, "I wrote this"
Write #fnum,
'use Print when you want the string without quotation marks
Print #fnum, "I printed this"
Close #fnum
End Sub
I tried the solutions located at Is it possible to run a macro in Excel from external command? to get this far (and modified of course) but it didn't seem to work. I keep getting the error `Microsoft Office Excel: The macro 'Macro.TestMacro' cannot be found.
EDIT: Excel 2003.
Ok, it's actually simple. Assuming that your macro is in a module,not in one of the sheets, you use:
objExcel.Application.Run "test.xls!dog"
'notice the format of 'workbook name'!macro
For a filename with spaces, encase the filename with quotes.
If you've placed the macro under a sheet, say sheet1, just assume sheet1 owns the function, which it does.
objExcel.Application.Run "'test 2.xls'!sheet1.dog"
Notice: You don't need the macro.testfunction notation you've been using.
This code will open the file Test.xls and run the macro TestMacro which will in turn write to the text file TestResult.txt
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Test.xls", 0, True)
xlApp.Run "TestMacro"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Echo "Finished."
WScript.Quit
Since my related question was removed by a righteous hand after I had killed the whole day searching how to beat the "macro not found or disabled" error, posting here the only syntax that worked for me (application.run didn't, no matter what I tried)
Set objExcel = CreateObject("Excel.Application")
' Didn't run this way from the Modules
'objExcel.Application.Run "c:\app\Book1.xlsm!Sub1"
' Didn't run this way either from the Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Sheet1.Sub1"
' Nor did it run from a named Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Named_Sheet.Sub1"
' Only ran like this (from the Module1)
Set objWorkbook = objExcel.Workbooks.Open("c:\app\Book1.xlsm")
objExcel.Run "Sub1"
Excel 2010, Win 7
I tried to adapt #Siddhart's code to a relative path to run my open_form macro, but it didn't seem to work. Here was my first attempt. My working solution is below.
Option Explicit
Dim xlApp, xlBook
dim fso
dim curDir
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open(curDir & "Excels\CLIENTES.xlsb", 0, true)
xlApp.Run "open_form"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Echo "Finished."
EDIT
I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:
Issues I was facing:
1 - I did not want to use the Workbook_Open Event as the excel is locked in read only.
2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.
I first wrote a macro to launch my userform while hiding the application:
Sub open_form()
Application.Visible = False
frmAddClient.Show vbModeless
End Sub
I then created a vbs to launch this macro (doing it with a relative path has been tricky):
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"
And I finally did a batch file to execute the VBS...
#echo off
pushd %~dp0
cscript Add_Client.vbs
Note that I have also included the "Set back to visible" in my Userform_QueryClose:
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
ThisWorkbook.Close SaveChanges:=True
Application.Visible = True
Application.Quit
End Sub
Anyway, thanks for your help, and I hope this will help if someone needs it
I tried the above methods but I got the "macro cannot be found" error.
This is final code that worked!
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
' Import Add-Ins
xlApp.Workbooks.Open "C:\<pathOfXlaFile>\MyMacro.xla"
xlApp.AddIns("MyMacro").Installed = True
'
Open Excel workbook
Set xlBook = xlApp.Workbooks.Open("<pathOfXlsFile>\MyExcel.xls", 0, True)
' Run Macro
xlApp.Run "Sheet1.MyMacro"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
In my case, MyMacro happens to be under Sheet1, thus Sheet1.MyMacro.
I generally store my macros in xlam add-ins separately from my workbooks so I wanted to open a workbook and then run a macro stored separately.
Since this required a VBS Script, I wanted to make it "portable" so I could use it by passing arguments. Here is the final script, which takes 3 arguments.
Full Path to Workbook
Macro Name
[OPTIONAL] Path to separate workbook with Macro
I tested it like so:
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"
runmacro.vbs:
Set args = Wscript.Arguments
ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
macrowb= WScript.Arguments.Item(2)
End If
LaunchMacro
Sub LaunchMacro()
Dim xl
Dim xlBook
Set xl = CreateObject("Excel.application")
Set xlBook = xl.Workbooks.Open(ws, 0, True)
If wscript.arguments.count > 2 Then
Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
End If
'xl.Application.Visible = True ' Show Excel Window
xl.Application.run macro
'xl.DisplayAlerts = False ' suppress prompts and alert messages while a macro is running
'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
'xl.activewindow.close
xl.Quit
End Sub
If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:
Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here
oExcel.DisplayAlerts = False
For Each oFile In oFSO.GetFolder("C:\Location\").Files
If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)
oExcel.Run wb2.Name & "!modForm"
For Each oSheet In .Worksheets
oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6
Next
.Close False, , False
End With
End If
Next
oExcel.Quit
oShell.Popup "Conversion complete", 10
So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.
Hi used this thread to get the solution , then i would like to share what i did just in case someone could use it.
What i wanted was to call a macro that change some cells and erase some rows, but i needed for more than 1500 excels( approximately spent 3 minuts for each file)
Mainly problem:
-when calling the macro from vbe , i got the same problem, it was imposible to call the macro from PERSONAL.XLSB, when the script oppened the excel didnt execute personal.xlsb and wasnt any option in the macro window
I solved this by keeping open one excel file with the macro loaded(a.xlsm)(before executing the script)
Then i call the macro from the excel oppened by the script
Option Explicit
Dim xl
Dim counter
counter =10
Do
counter = counter + 1
Set xl = GetObject(, "Excel.Application")
xl.Application.Workbooks.open "C:\pruebas\macroxavi\IA_030-08-026" & counter & ".xlsx"
xl.Application.Visible = True
xl.Application.run "'a.xlsm'!eraserow"
Set xl = Nothing
Loop Until counter = 517
WScript.Echo "Finished."
WScript.Quit
So I am having a problem uploading files from RStudio to Excel for MATLAB processing.
I had this problem before with formulas not being populated, so I made a script to open, save, and close the Excel file which then worked fine for populating the formulas and loading the numerical values back into RStudio. However I can not figure out how to open multiple .csv files that have changing names depending on our sample ID.
Heres my script that I tried to have open up multiple files:
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\PCRdata\*.csv")
## Also tried Set objWorkbook = objExcel.Workbooks.Open("C:\PCRdata\"& "*.csv")
objExcel.Application.Visible = True
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
WScript.Echo "Your Excel Spreadsheet was Updated, Open these files in Matlab"
WScript.Quit
However the script doesnt like the * to call upon all files, is there another way I can do this? or a better way to have RStudios come out with data that is usable to matlab.
MATLAB Error:
Error using netest/testingBrowseButton_Callback (line 63)
Cannot concatenate the table variables 'AKAP8L' and 'ARAF', because their types are double and cell.
Error while evaluating UIControl Callback
Well did some digging on the website and found an alternative post that used a script to change change xls to xslx so I just made it so it went from csv to csv. Hope this helps anyone else that had this problem.
Set app = CreateObject("Excel.Application")
app.Visible = False
app.DisplayAlerts = False
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder("C:\PCRdata").Files
If LCase(fso.GetExtensionName(f)) = "csv" Then
Set wb = app.Workbooks.Open(f.Path)
wb.Save
wb.Close True
End if
Next
app.Quit
Set f = Nothing
Set app = Nothing
Set fso = Nothing
wScript.Quit
I have an MS Excel 2013 file containing a PowerPivot Data Model. The model is based on several text files (CSV files). The files are updated every night automatically. After these files update, the MS Excel file should be updated as well.
I open the MS Excel file and hit the "Refresh All" Button, everything works as expected. Of course this task should be automated. For this purpose I programmed a small vbscript:
Option Explicit
Dim objShell, objShortCut, objFSO, objFile, objXLApp, objXLWB
Dim strShortCut
strShortCut = "\\myserver\share\Dashboard.lnk"
Set objShell = CreateObject ("WScript.Shell")
Set objShortCut = objShell.CreateShortCut(strShortCut)
Set objFSO = CreateObject ("Scripting.FileSystemObject")
Set objFile = objFSO.getFile(objShortCut.TargetPath)
if (objFile.attributes and 1) then
'File is read only. make it read/write-able
objFile.attributes = objFile.attributes - 1
end if
' This is the interesting part
Set objXLApp = CreateObject("Excel.Application")
objXLApp.Visible = True
WScript.Echo "Excel Started"
objXLApp.Calculation = -4135
Set objXLWB = objXLApp.Workbooks.Open(objShortCut.TargetPath)
WScript.Echo "Dashboard Opened"
objXLWB.Model.Initialize
WScript.Echo "Model Initialized"
objXLWB.Model.Refresh
WScript.Echo "Model Refreshed"
objXLApp.Calculation = -4105
objXLWB.save
WScript.Echo "Workbook saved"
objXLWB.close (false)
objXLApp.Quit
WScript.Echo "Excel closed"
if (not (objFile.attributes and 1)) then
'File is read/write. Make it read-only.
objFile.attributes = objFile.attributes + 1
end if
Set objShell = Nothing
Set objFile = Nothing
Set objFSO = Nothing
Set objShortCut = Nothing
Set objXLApp = Nothing
Set objXLWB = Nothing
This script updates the data, but some columns in the text files contain numbers with trailing minus signs (for negative numbers). These columns are treated as text and therefore successive calculations on these columns fail.
This is not a problem if I refresh the MS Excel files by hand as described above. What's the difference from running Excel through a vbscript or "normally"?
I have the following workbook setup:
Workbook A has a link to x amount of workbook B's and fetches data from them. The workbooks B have links to some other workbooks and fetches data from them.
Workbook A is a kind of "summary" of what all the other workbooks contains. As it is now, I have to open all my workbook Bs, refresh them and save before I open workbook A. If I don't do this the workbook B's will not be updated with the data in the workbooks C.
Is it possible to update all the workbook B's using a .bat or vbs script? or is it possible to update them from within workbook A?
I might add that I use excel starter on this computer so preferly the solution would be compatible with that.
Attached is one potential solution for this as a vbs that can be run from vba if that is available
Thanks to Sid Rout for his suggested edits to RecursiveFile(objWB)
Caution: It is possible that too many simultaneous books being open (I got to 512 during vbs recursion hell) will lead to memory issues - in that case each major branch should be updated in turn, then those workbooks closed before proceeding to the next branch.
What it does
Opens up a workbook held by strFilePath
checks whether there are any linked workbooks in 1 , if so opens them (B, B1, B2 etc)
the code then looks for any links in each of the workbooks from (2), then opens all these in turn (C1 and C2 for B etc)
each open book name is stored in an array, Arr
When all the books are opened, the initial workbook will have been updated, the recursive code ends, and all the open books except strFilePath are closed without saving
strFilePath is then saved and closed
the code tidies up
EDIT: Updated code to fix the vbs recursion issue
Public objExcel, objWB2, lngCnt, Arr()
Dim strFilePath, vLinks
`credit to Sid Rout for updating `RecursiveFileRecursiveFile(objWB)`
Erase Arr
lngCnt = 0
Set objExcel = CreateObject("Excel.Application")
strFilePath = "C:\temp\main.xlsx"
With objExcel
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
End With
Set objWB = objExcel.Workbooks.Open(strFilePath, False)
Call RecursiveFile(objWB)
For Each vArr In Arr
objExcel.Workbooks(vArr).Close False
Next
objWB.Save
objWB.Close
Set objWB2 = Nothing
With objExcel
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
.Quit
End With
Set objExcel = Nothing
MsgBox "Complete"
Sub RecursiveFile(objWB)
If Not IsEmpty(objWB.LinkSources()) Then
For Each vL In objWB.LinkSources()
ReDim Preserve Arr(lngCnt)
'MsgBox "Processing File " & vL
Set objWB2 = objExcel.Workbooks.Open(vL, False)
Arr(lngCnt) = objWB2.Name
lngCnt = lngCnt + 1
RecursiveFile objWB2
Next
End If
End Sub
Working ScreenShots
yes, you can loop through all the source B workbooks, opening them in the background and set the UpdateLinks flag to True ...
strFiles=Dir(*path & \.xls*)
do
workbooks.open strfiles, UpdateLinks:=true
workbooks(strfiles).close savechanges:=true
strFiles=Dir
loop while strfiles<>""
that should give you a start
So, as VBA is not an option, let's try a VB Script solution:
dim objFSO, objExcel, objWorkbook, objFile
'
set objExcel= CreateObject("Excel.application")
'
objExcel.visible=false
objExcel.displayalerts=false
'
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = path
'
Set objFolder = objFSO.GetFolder(objStartFolder)
' get collection of files from folder
Set colFiles = objFolder.Files
' begin loop through all files returned by Files collection of Folder object
For Each objFile in colFiles
' sanity check, is the file an XLS file?
if instr(objfile.name,"xls")<>0 then ' could also use right(objfile.name,4)=...
Wscript.Echo "Opening '" objFile.Name & "' ..."
set objWorkbook=objexcel.workbooks.open objfile.name, updatelinks:=true
objexcel.workbooks(objfile.name).close savechanges:=true
end if
Next
' close Excel
objexcel.quit
' kill the instance and release the memory
set objExcel=nothing
try that and see how you get on
and here is the VB Script SDK: MSDN Library - VB Script
I'm trying to run an Excel macro from outside of the Excel file. I'm currently using a ".vbs" file run from the command line, but it keeps telling me the macro can't be found. Here is the script I'm trying to use
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("test.xls")
objExcel.Application.Visible = True
objExcel.Workbooks.Add
objExcel.Cells(1, 1).Value = "Test value"
objExcel.Application.Run "Macro.TestMacro()"
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
WScript.Echo "Finished."
WScript.Quit
And here is the Macro I'm trying to access:
Sub TestMacro()
'first set a string which contains the path to the file you want to create.
'this example creates one and stores it in the root directory
MyFile = "C:\Users\username\Desktop\" & "TestResult.txt"
'set and open file for output
fnum = FreeFile()
Open MyFile For Output As fnum
'write project info and then a blank line. Note the comma is required
Write #fnum, "I wrote this"
Write #fnum,
'use Print when you want the string without quotation marks
Print #fnum, "I printed this"
Close #fnum
End Sub
I tried the solutions located at Is it possible to run a macro in Excel from external command? to get this far (and modified of course) but it didn't seem to work. I keep getting the error `Microsoft Office Excel: The macro 'Macro.TestMacro' cannot be found.
EDIT: Excel 2003.
Ok, it's actually simple. Assuming that your macro is in a module,not in one of the sheets, you use:
objExcel.Application.Run "test.xls!dog"
'notice the format of 'workbook name'!macro
For a filename with spaces, encase the filename with quotes.
If you've placed the macro under a sheet, say sheet1, just assume sheet1 owns the function, which it does.
objExcel.Application.Run "'test 2.xls'!sheet1.dog"
Notice: You don't need the macro.testfunction notation you've been using.
This code will open the file Test.xls and run the macro TestMacro which will in turn write to the text file TestResult.txt
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open("C:\Test.xls", 0, True)
xlApp.Run "TestMacro"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Echo "Finished."
WScript.Quit
Since my related question was removed by a righteous hand after I had killed the whole day searching how to beat the "macro not found or disabled" error, posting here the only syntax that worked for me (application.run didn't, no matter what I tried)
Set objExcel = CreateObject("Excel.Application")
' Didn't run this way from the Modules
'objExcel.Application.Run "c:\app\Book1.xlsm!Sub1"
' Didn't run this way either from the Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Sheet1.Sub1"
' Nor did it run from a named Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Named_Sheet.Sub1"
' Only ran like this (from the Module1)
Set objWorkbook = objExcel.Workbooks.Open("c:\app\Book1.xlsm")
objExcel.Run "Sub1"
Excel 2010, Win 7
I tried to adapt #Siddhart's code to a relative path to run my open_form macro, but it didn't seem to work. Here was my first attempt. My working solution is below.
Option Explicit
Dim xlApp, xlBook
dim fso
dim curDir
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open(curDir & "Excels\CLIENTES.xlsb", 0, true)
xlApp.Run "open_form"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Echo "Finished."
EDIT
I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:
Issues I was facing:
1 - I did not want to use the Workbook_Open Event as the excel is locked in read only.
2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.
I first wrote a macro to launch my userform while hiding the application:
Sub open_form()
Application.Visible = False
frmAddClient.Show vbModeless
End Sub
I then created a vbs to launch this macro (doing it with a relative path has been tricky):
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"
And I finally did a batch file to execute the VBS...
#echo off
pushd %~dp0
cscript Add_Client.vbs
Note that I have also included the "Set back to visible" in my Userform_QueryClose:
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
ThisWorkbook.Close SaveChanges:=True
Application.Visible = True
Application.Quit
End Sub
Anyway, thanks for your help, and I hope this will help if someone needs it
I tried the above methods but I got the "macro cannot be found" error.
This is final code that worked!
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
' Import Add-Ins
xlApp.Workbooks.Open "C:\<pathOfXlaFile>\MyMacro.xla"
xlApp.AddIns("MyMacro").Installed = True
'
Open Excel workbook
Set xlBook = xlApp.Workbooks.Open("<pathOfXlsFile>\MyExcel.xls", 0, True)
' Run Macro
xlApp.Run "Sheet1.MyMacro"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
In my case, MyMacro happens to be under Sheet1, thus Sheet1.MyMacro.
I generally store my macros in xlam add-ins separately from my workbooks so I wanted to open a workbook and then run a macro stored separately.
Since this required a VBS Script, I wanted to make it "portable" so I could use it by passing arguments. Here is the final script, which takes 3 arguments.
Full Path to Workbook
Macro Name
[OPTIONAL] Path to separate workbook with Macro
I tested it like so:
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlam" "Hello"
"C:\Temp\runmacro.vbs" "C:\Temp\Book1.xlsx" "Hello" "%AppData%\Microsoft\Excel\XLSTART\Book1.xlam"
runmacro.vbs:
Set args = Wscript.Arguments
ws = WScript.Arguments.Item(0)
macro = WScript.Arguments.Item(1)
If wscript.arguments.count > 2 Then
macrowb= WScript.Arguments.Item(2)
End If
LaunchMacro
Sub LaunchMacro()
Dim xl
Dim xlBook
Set xl = CreateObject("Excel.application")
Set xlBook = xl.Workbooks.Open(ws, 0, True)
If wscript.arguments.count > 2 Then
Set macrowb= xl.Workbooks.Open(macrowb, 0, True)
End If
'xl.Application.Visible = True ' Show Excel Window
xl.Application.run macro
'xl.DisplayAlerts = False ' suppress prompts and alert messages while a macro is running
'xlBook.saved = True ' suppresses the Save Changes prompt when you close a workbook
'xl.activewindow.close
xl.Quit
End Sub
If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:
Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here
oExcel.DisplayAlerts = False
For Each oFile In oFSO.GetFolder("C:\Location\").Files
If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)
oExcel.Run wb2.Name & "!modForm"
For Each oSheet In .Worksheets
oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6
Next
.Close False, , False
End With
End If
Next
oExcel.Quit
oShell.Popup "Conversion complete", 10
So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.
Hi used this thread to get the solution , then i would like to share what i did just in case someone could use it.
What i wanted was to call a macro that change some cells and erase some rows, but i needed for more than 1500 excels( approximately spent 3 minuts for each file)
Mainly problem:
-when calling the macro from vbe , i got the same problem, it was imposible to call the macro from PERSONAL.XLSB, when the script oppened the excel didnt execute personal.xlsb and wasnt any option in the macro window
I solved this by keeping open one excel file with the macro loaded(a.xlsm)(before executing the script)
Then i call the macro from the excel oppened by the script
Option Explicit
Dim xl
Dim counter
counter =10
Do
counter = counter + 1
Set xl = GetObject(, "Excel.Application")
xl.Application.Workbooks.open "C:\pruebas\macroxavi\IA_030-08-026" & counter & ".xlsx"
xl.Application.Visible = True
xl.Application.run "'a.xlsm'!eraserow"
Set xl = Nothing
Loop Until counter = 517
WScript.Echo "Finished."
WScript.Quit