I have an Excel file named "ABCD.xlsm" in three different folders.
When I open these files using VBScript one after the other I cannot run the macros and the addin.
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile("D:\Temp\Excellocation.txt", 1, False)
Do While theFile.AtEndOfStream <> True
retstring = retstring & theFile.ReadLine
Loop
theFile.Close
lx_loc = retstring
fso.DeleteFile "D:\Temp\Excellocation.txt"
set objExcel = Createobject("Excel.Application")
objExcel.visible = True
objExcel.workbooks.open(lx_loc)
msgBox "RUN macro CallVSTOMethod and press ok",1, true
In the code the text file has the location of the Excel file.
If there is only one use of this code, then I have no issues. When I call this function more than once, I can't run the addin or the macro.
It is because when you open your file with a connection, it is locking this file, so you cannot open it for that reason. What you can do, is copy past a duplicate and open the copy. It will open right away! ;)
Related
I have a xlsx macro enabled file . How can I set it in the task manager so that everyday at 9 AM task manager would open the workbook, fire the macro and close the workbook.
So far i am using
Application.OnTime . . .
But i realize that keeping the xlsm file open is inconvenient
Better to use a vbs as you indicated
Create a simple vbs, which is a text file with a .vbs extension (see sample code below)
Use the Task Scheduler to run the vbs
Use the vbs to open the workbook at the scheduled time and then either:
use the Private Sub Workbook_Open() event in the ThisWorkbook module to run code when the file is opened
more robustly (as macros may be disabled on open), use Application.Run in the vbs to run the macro
See this example of the later approach at Running Excel on Windows Task Scheduler
sample vbs
Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run
ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing
Three important steps - How to Task Schedule an excel.xls(m) file
simply:
make sure the .vbs file is correct
set the Action tab correctly in Task Scheduler
don't turn on "Run whether user is logged on or not"
IN MORE DETAIL...
Here is an example .vbs file:
`
' a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt to .vbs
'Write Excel.xls Sheet's full path here
strPath = "C:\RodsData.xlsm"
'Write the macro name - could try including module name
strMacro = "Update" ' "Sheet1.Macro2"
'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application")
objApp.Visible = True ' or False
'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath)
objApp.Run strMacro ' wbToRun.Name & "!" & strMacro
wbToRun.Save
wbToRun.Close
objApp.Quit
'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!", vbInformation
'
`
In the Action tab (Task Scheduler):
set Program/script: = C:\Windows\System32\cscript.exe
set Add arguments (optional): = C:\MyVbsFile.vbs
Finally, don't turn on "Run whether user is logged on or not".
That should work.
Let me know!
Rod Bowen
I referred a blog by Kim for doing this and its working fine for me. See the blog
The automated execution of macro can be accomplished with the help of a VB Script file which is being invoked by Windows Task Scheduler at specified times.
Remember to replace 'YourWorkbook' with the name of the workbook you want to open and replace 'YourMacro' with the name of the macro you want to run.
See the VB Script File (just named it RunExcel.VBS):
' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone
' Tell Excel what the current working directory is
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\YourWorkbook.xls"
Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)
' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "'" & strPath & "\YourWorkbook" & "!Sheet1.YourMacro"
on error resume next
' Run the calculation macro
myExcelWorker.Run strMacroName
if err.number <> 0 Then
' Error occurred - just close it down.
End If
err.clear
on error goto 0
oWorkBook.Save
myExcelWorker.DefaultFilePath = strSaveDefaultPath
' Clean up and shut down
Set oWorkBook = Nothing
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
if myExcelWorker.Workbooks.Count = 0 Then
myExcelWorker.Quit
End If
Set myExcelWorker = Nothing
Set WshShell = Nothing
You can test this VB Script from command prompt:
>> cscript.exe RunExcel.VBS
Once you have the VB Script file and workbook tested so that it does what you want, you can then use Microsoft Task Scheduler (Control Panel-> Administrative Tools--> Task Scheduler) to execute ‘cscript.exe RunExcel.vbs’ automatically for you.
Please note the path of the macro should be in correct format and inside single quotes like:
strMacroName = "'" & strPath & "\YourWorkBook.xlsm'" &
"!ModuleName.MacroName"
Code below copied from -> Here
First off, you must save your work book as a macro enabled work book. So it would need to be xlsm not an xlsx. Otherwise, excel will disable the macro's due to not being macro enabled.
Set your vbscript (C:\excel\tester.vbs). The example sub "test()" must be located in your modules on the excel document.
dim eApp
set eApp = GetObject("C:\excel\tester.xlsm")
eApp.Application.Run "tester.xlsm!test"
set eApp = nothing
Then set your Schedule, give it a name, and a username/password for offline access.
Then you have to set your actions and triggers.
Set your schedule(trigger)
Action, set your vbscript to open with Cscript.exe so that it will be executed in the background and not get hung up by any error handling that vbcript has enabled.
I found a much easier way and I hope it works for you. (using Windows 10 and Excel 2016)
Create a new module and enter the following code:
Sub auto_open()
'Macro to be run (doesn't have to be in this module, just in this workbook
End Sub
Set up a task through the Task Scheduler and set the "program to be run as" Excel (found mine at C:\Program Files (x86)\Microsoft Office\root\Office16). Then set the "Add arguments (optional): as the file path to the macro-enabled workbook. Remember that both the path to Excel and the path to the workbook should be in double quotes.
*See example from Rich, edited by Community, for an image of the windows scheduler screen.
edited to be more specific:
VBScript below runs through entire folder, opens each *.XLSM file there, refreshes all data connections and saves updated files one by one. Files are also password protected, but it's not that important.
How to enhance the code to AVOID files in folder, based on part or entire filename? For an example avoid filenames ending with z however with still .xlsm extension.
Expected outcome for files located in the same folder:
abc123.xlsm (refresh); abc123z.xlsm (avoid); file.xlsm (refresh);
testz.xlsm (avoid)
Set fso = CreateObject("Scripting.FileSystemObject")
Set xl = CreateObject("Excel.Application")
xl.Visible = False
For Each f In fso.GetFolder("C:\test\").Files
If LCase(fso.GetExtensionName(f.Name)) = "xlsm" Then
Set wb = xl.Workbooks.Open(f.Path ,,,,,"x")
wb.RefreshAll
wb.Save
wb.Close
End If
Next
xl.Quit
you can try use split command.
file_path =abc123.xlsm
file_name =split(file_path,".")
file_name is an array containing 2 values
file_name (0)=abc123
file_name (1)=xlsm
now you can check if the last char in file_name(0)="Z"
if NOT(right(file_name(0),1)="Z") THEN
do...
ELSE
do...
END IF
I have a set of excel files that open in protected view. I would like to open these excel files, remove the protected view, then save them as tab delimited text files. So far, I have been able to do everything but when I run the script, a prompt comes up asking if the user would like to save the excel file. I want to get rid of this prompt to make the script fully automatic. Here is the current code:
format = -4158
Set objFSO = CreateObject("Scripting.FileSystemObject")
src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(1))
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
oExcel.ProtectedViewWindows.Open(src_file)
oExcel.ActiveProtectedViewWindow.Edit
oExcel.Quit
Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)
oBook.Worksheets(5).Activate
oBook.SaveAs dest_file, format
oBook.Close False
oExcel.Quit
I have found solutions to removing the prompt online, but because I have to edit the protected view window, I could not find a way to use the solutions. How can I make it so that this VB script removes the protected view, and saves the excel file as a tab delimited text file? It should do this without showing any windows or prompts, i.e., it should be automatic.
To simply have Excel ignore message boxes in general it is like this:
oExcel.DisplayAlerts = False
'your code here to close workbook
oExcel.DisplayAlerts = True
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
For a few reasons discussed here I can't open an excel worksheet like this:
Set excel = CreateObject("Excel.Application")
Set workbook = excel.Workbooks.Open(file_path.xls)
excel.Visible = True
So I'm trying to open it like this:
CreateObject("WScript.Shell").Run "excel.exe"
WScript.Sleep 5000
CreateObject("WScript.Shell").Run "excel.exe"
WScript.Sleep 5000
Set excel = GetObject(,"Excel.Application")
Set workbook = excel.Workbooks.Open( excel_file_path, 3)
excel.Visible = True
This runs just fine when my computer isn't locked. And usually VBScripts can run even when a computer is locked. However, only when the computer is locked, at the line GetObject(,"Excel.Application") I get the following runtime error:
Error: ActiveX component can't create object: 'GetObject'
Code: 800A01AD
Source: Microsoft VBScript runtime error
I tried changing my Windows 7 settings to never lock after some inactivity, but my company's IT department has enforced that setting.
Is there a way to run this script from a locked screen, or is there an alternative you recommend?
Edit:
It has something to do with the way the excel file is being opened... If I open a new blank excel page than lock the screen, GetObject will work just fine getting that document, but if I open it using the shell then log out, it won't...
In the section that does not seem to work, add this line after setting visible = TRUE, and see if your calculations then work as expected:
CreateObject("WScript.Shell").AppActivate objExcel.Name
Not sure if it will work, but I am doing similar things in some code and this is what's there.
I must have copied or read about it somewhere (wish I could give credit to where).
FYI - I have a vbscript that opens Excel, starts a new workbook, reads a file in as text via a querytable object, then does some automated edits. The code that works for me is:
...
set objExcel = CreateObject("Excel.application")
' Commented out the following line, so the user can see something is happening.
' objExcel.application.screenupdating = false ' Don't update the screen while shucking and jiving is going on.
objExcel.visible = true
objExcel.application.cursor = 2 ' change cursor to the hourglass.
CreateObject("WScript.Shell").AppActivate objExcel.Name
' Create a new workbook and worksheet
objExcel.workbooks.add
objExcel.worksheets.add
etc
Try the code:
CreateObject("WScript.Shell").Run "excel.exe """ & excel_file_path & """"
WScript.Sleep 5000
CreateObject("WScript.Shell").Run "excel.exe"
WScript.Sleep 5000
Set excel = GetObject(,"Excel.Application")