I'm trying to write a vbscript to be able to checkout an excel file that is stored on sharepoint server.
Currently I can check the file out from SharePoint 2010: Link to open Excel file in edit-mode mode
However, I'm trying to check the file back in but not able to. I've searched and tried the checkout functions per http://msdn.microsoft.com/en-us/library/office/ff194456%28v=office.14%29.aspx but not able to.
Currently the code I have is
Sub CheckInFile
Dim ExcelApp, ExcelSheet, ExcelBook
Dim myURL
myURL = "http://server/Site/excel.xlsx"
Set ExcelApp = CreateObject("Excel.Application")
If (ExcelApp.WorkBooks.CanCheckIn(myURL) = True) Then
msgbox ("here")
ExcelApp.WorkBooks.Open (myURL)
ExcelApp.Application.WorkBooks.CheckIn myURL
ExcelApp.ActiveWorkbook.Close
' Quit Excel.
ExcelApp.Quit
' Clean Up
Set ExcelApp= Nothing
End If
End Sub
However the script stops and fails at the if statement, rather doesn't execute. Is there a similar vbscript function to check in a file ?
I struggled a LOT with this and spent many hours searching for a solution that worked in my particular environment. Here are my criteria that needed to be met:
Execute the process from my computer using vbscript file
Iterate through a list of ~200 excel spreadsheets
Check out each file
Make various conditional updates and save
Check the file back in again when updates are complete.
Below is an alternate solution for anybody in the future that, like me, tried the suggested approach and it didn't work. This is tested and working:
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Dim MyVar ' so popup alerts narrate the process
' and help explain what is happening
' for those who want to see it step
' by step
Dim docPath
docPath = "\\your server\sites\Docs\sharepoint spreadsheet.xlsx"
' I believe this can be any document path
Set objWorkbook = objExcel.Workbooks.Open(docPath)
cco = objExcel.Workbooks.CanCheckOut(docPath)
MyVar = MsgBox ("can check out? " & cco, 0)
' -----------------------------------------------------
' this shows "False" every time. I still do not know how
' to get this to work, but thought it would be valuable
' to include for explanation
' -----------------------------------------------------
objExcel.Workbooks.CheckOut(docPath)
' -----------------------------------------------------
' this SUCCEEDS every time...as long as you have
' the ability to check out the document manually
' -----------------------------------------------------
MyVar = MsgBox ("Update cell", 0)
With objExcel.ActiveWorkbook.Worksheets(1)
objExcel.Cells( 1, 1 ).Value = "test value"
End With
MyVar = MsgBox ("Save the file", 0)
objWorkbook.Save
MyVar = MsgBox ("check in the file", 0)
objWorkbook.CheckIn
' -----------------------------------------------------
' This actually checks in the active document and *closes
' it* You don't have to have a separate command to close
' the file, e.g.
' objWorkbook.Close
' THIS WILL FAIL.
' -----------------------------------------------------
Set objWorkbook = Nothing
Just try this:
Dim ExcelApp, ExcelSheet, ExcelBook
Dim myURL = "http://server/Site/excel.xlsx"
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.WorkBooks.Open (myURL)
If (ExcelApp.ActiveWorkbook.CanCheckIn = True) Then
ExcelApp.Application.WorkBooks(myURL).CheckIn
ExcelApp.ActiveWorkbook.Close
' Quit Excel.
ExcelApp.Quit
' Clean Up
Set ExcelApp= Nothing
End If
Just change include below lines to your code:
ExcelApp.Visible = True
ExcelApp.DisplayAlerts = False
Thanks!
Dim oExcel
Dim strFileName
Set oExcel = CreateObject("Excel.Application")
oExcel.Visible = True
oExcel.DisplayAlerts = False
strFileName = "view_2019.xlsm"
'Checkin
If oExcel.Workbooks(strFileName).CanCheckIn = True Then
oExcel.Workbooks(strFileName).CheckIn SaveChanges=True,Comments="Updated"
MsgBox strFileName & " has been checked in."
Else
MsgBox "This file cannot be checked in at this time. Please try again later."
End If
set oExcel = nothing
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
I have script that printing specific file, but it's getting hard to make over 150 .vbs files for each document to be printed,
is there any way to have pop-out window where i can type file name, then script find it in folder and print it with 20 copies.
I have PDF, WORD and Excel files
this is what i have now for them
Dim AppExcel
Set AppExcel = CreateObject("Excel.application")
AppExcel.Workbooks.Open"directory\filename.xlsx"
AppExcel.Visible = True
AppExcel.ActiveWindow.SelectedSheets.PrintOut,,20
Appexcel.Quit
Set appExcel = Nothing
filename = "\\MCSERVER01\Data\Forms\Vehicle inspection forms\daily vehicle inspection form.pdf"
Set sh = CreateObject("WScript.Shell")
sh.Run "sumatrapdf.exe -print-to-default """ & filename & """", 0, True
Dim AppWord
Set AppWord = CreateObject("Word.application")
AppWord.Documents.Open"\\MCSERVER01\Data\Forms\DODD\SMALL CAR DRIVERS\Akira Litman.docx"
AppWord.Visible = True
AppWord.ActiveDocument.PrintOut
AppWord.Quit
Set appWord = Nothing
Perhaps you can make use of an input box
Dim fileToPrint As String
fileToPrint = InputBox("Enter file name to print")
I got some help from my old friend, but now i can't get another part working
set fso = CreateObject("Scripting.FileSystemObject")
call main
sub main
InputName = InputBox("ENTER YOUR NAME")
if instr(InputName, ".") = 0 then
msgbox("DON'T NEED THIS AT ALL!!!!!")
exit sub
end if
'msgbox(mid(InputName, instr(InputName, ".")+1))
select case mid(InputName, instr(InputName, ".")+1)
case "xlsx"
call printExcel(InputName)
end select
end sub
sub printExcel(fileName)
Dim AppExcel, path
Set AppExcel = CreateObject("Excel.application")
path = "\MCSERVER01\Data\Forms\Access2Care\WHEELCHAIR DRIVERS\"
if fso.FileExists(path & fileName) then
AppExcel.Workbooks.Open path & fileName
AppExcel.Visible = false
AppExcel.ActiveWindow.SelectedSheets.PrintOut,,20
Appexcel.Quit
Set appExcel = Nothing
else
X=MsgBox ("Wrong File Name Or File Doesn't Exist" ,0+16, "Please Re-Enter Your Full Name")
end if
end sub
so the issue i have now is that i have to type in file extension to make it work otherwise im getting msgbox with "don't need this"
how i can get rid of that msg and just have default extension as xlsx xsl
I've got a strange issue in my small VBA/Excel app. I've got a vbs script which starts an Excel Macro:
Option Explicit
Dim excelObject
Set excelObject = CreateObject("Excel.Application")
excelObject.DisplayAlerts = False
excelObject.AskToUpdateLinks = False
excelObject.AlertBeforeOverwriting = False
excelObject.WorkBooks.Open "C:\test\test.xlsm", 0, True
excelObject.Run "Make_Output.Update_Data_In_Another_Excel_Document"
excelObject.Quit(0)
this Excel Macro opens another Excel document and modifies some data there.
My problem happens when I run it from command line. Sometimes I receive error : "File not found: " exception although I haven't changed anything in the app. For instance when I run the app on another machine. When I open the Excel doc and run it manually from Excel Macro editor all is fine. I have no idea what can be the issue although I've already went through the manual. Maybe it is connected with compilation of macros by EXCEL.
Additional info:
Version: Microsoft Excel 2010 - 14.0.7015 - 32-bit but my system is 64-bit
Any hints appreciated.
Thanks.
foxrafi
My VBScript File (OpenExcel.vbs)
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set xlApp = CreateObject("Excel.Application")
File = oFSO.GetParentFolderName(Wscript.ScriptFullName) & _
"\run this to open other files macro.xlsm"
xlApp.DisplayAlerts = False
Set xlWorkBook = xlApp.Workbooks.Open(File)
xlApp.Visible = True 'or False
xlApp.Run "'C:\Users\Pavle\Desktop\testvbscript.xlsm'!TestVBScript"
The Macro in that sheet
Sub Meow()
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open ("C:\Users\Pavle\Desktop\testvbscript.xlsm")
objExcel.Visible = True
objExcel.Run "'C:\Users\Pavle\Desktop\testvbscript.xlsm'!TestVBScript"
objExcel.ActiveWorkbook.Close
objExcel.Quit
Set objExcel = Nothing
End Sub
Then the last macro to open random file to modify cell
Sub TestVBScript()
MsgBox "Running VBScript to run this macro worked."
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FileExists("C:\Users\Pavle\Desktop\test.xlsx") Then
Set FileToModify = Workbooks.Open("C:\Users\Pavle\Desktop\test.xlsx")
Set OpenFile = FileToModify.Sheets("Sheet1")
OpenFile.Cells(1, "A").Value = "OOOHHH YEAAHHHH."
FileToModify.Save
FileToModify.Close
Debug.Print "yes"
Else
Debug.Print "no"
End If
End Sub
Good Morning All,
I have fought with this for a few days now, and have not yet found a suitable solution, so I hope somebody can put me out of my misery!
From within an excel document, I have 3 buttons to check out and open 3 documents from a Microsoft Sharepoint Server. 2 files are Excel workbooks, and one is a Word document.
The excel files work absolutely fine, but the Word document always returns 'False' when the .CanCheckOut statement is reached, even though I can manually check it out on MOSS, have the correct permissions etc. I have added the Microsoft Word 11.0 Object Library reference in my Excel VBA.
Here is my code for the excel ones:
Sub CheckOutXL(FullPath As String)
Dim xlApp As Object
Dim wb As Workbook
Dim xlFile As String
xlFile = FullPath
Set xlApp = CreateObject("Excel.Application")
'Determine if workbook can be checked out.
If Workbooks.CanCheckOut(xlFile) = True Then
'Check out file
Workbooks.CheckOut xlFile
'Open File
Set xlApp = New Excel.Application
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(xlFile, , False)
'Otherwise offer the option to open read-only
Else
If (MsgBox("You are unable to check out this document at this time, would you like to open it read-only?", vbYesNo) = vbYes) Then
Set xlApp = New Excel.Application
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(xlFile, , False)
End If
End If
and for the Word one:
Sub CheckOutDoc(FullPath As String)
If Documents(docFile).CanCheckOut = True Then 'This is the one that returns FALSE
Documents.CheckOut docFile
' Set objWord = CreateObject("Word.Application") 'The commented out section was
' objWord.Visible = True 'a second way I tried to open
' objWord.Documents.Open docFile 'the file.
Documents.Open Filename:=docFile
Else
If (MsgBox("You are unable to check out this document at this time, would you like to open it read-only?", vbYesNo) = vbYes) Then
Documents.Open Filename:=docFile
End If
End If
End Sub
These are both called using a simple line for each button as such:
Private Sub btnTrend_Click()
Call CheckOutXL("FullPathOfTheFileInHere.xls")
End Sub
Any help massively appreciated!! Thanks
We are having the same issue. Can you try this:
If CBool(Documents(docFile).CanCheckOut) = True Then
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