Creating VBScript file Excel - excel

I don't have much knowledge in creating a VBScript file. I have a code i want to automate to send email out every month. With some research i found the code below:
dim EXL
set EXL = CreateObject("Excel.Application")
'not required
EXL.Visible = true
'your file and macro
EXL.Workbooks.Open "full path to your excel file including extension here"
EXL.Run "Fixing"
'close everything
EXL.Quit
Set EXL = Nothing
My Question is: do i implement this code into my excel module or is in the worksheet event?
Once i have this correctly applied i will be able to set the Windows Task Scheduler to run at the particular time.

Just save the VBscript file as a *.vbs file. Create a text file (txt), copy your code and save the file with the vbs extension. Next go to the Windows Task Scheduler and choose Run a Program and locate your VBS.
Sending emails from VBscript
http://www.analystcave.com/excel-send-email-excel-workbook/
Scheduling programs to run in Windows
http://windows.microsoft.com/en-au/windows/schedule-task#1TC=windows-7

Related

How can Rundeck launch Excel file on my machine?

I have a user interface that generates, on a directory called BatForRundeck, a set of CSV files (several per user), xlsm files (one per user) and .bat files (one per user).
The processing of these CSV files is done by the generated xlsm file. This xlsm is launched by a VBScript file with parameters but common to all users.
The VBScript file is started by the generated .bat.
This processing chain should be automated using Rundeck.
I am using a new .bat that loops over the BatForRundeck directory to process user generated .bat. The code is as following:
#echo off
for %%f in (C:\Users\myUserName\Documents\BatForRundeck\*10000*.bat) do call %%f
This .bat program works fine on my PC. But on Rundeck, this program runs but it does not launch Excel (xlsm) and CSV files are not processed.
I then tried another variant:
#echo off
for %%f in (C:\Users\myUserName\Documents\BatForRundeck\*10000*.bat) do echo call %%f >> C:\Users\myUserName\Documents\BatForRundeck\toto.bat
start C:\Users\myUserName\Documents\BatForRundeck\toto.bat
Remarque : I didn't delete toto.bat, because I wanted to see what it contains.
I have the same result, this .bat works fine on my PC. But on Rundeck, this program does not launch Excel (xlsm).
Example content of toto.bat:
call C:\Users\myUserName\Documents\BatForRundeck\Macro_RSI_V10_4-10000442896544.bat
call C:\Users\myUserName\Documents\BatForRundeck\Macro_RSI_V10_4-10000880367985.bat
The .bat Macro_RSI_V10_4-10000442896544.bat has the following code :
#echo off
C:\Users\myUserName\Documents\BatForRundeck\Macro_RSI_V10_4.OID.vbs Macro_RSI_V10_4.10000442896544.xlsm
And the Macro_RSI_V10_4-10000880367985.bat contains:
#echo off
C:\Users\myUserName\Documents\BatForRundeck\Macro_RSI_V10_4.OID.vbs Macro_RSI_V10_4.10000880367985.xlsm
The VBS Macro_RSI_V10_4.OID.vbs program contains the following code:
'Microsoft Excel Automation Basics
':: Open and Execute an Excel File.
'---------------------------------
'Retrieve the parameters that were passed.
Dim Arg
Set Arg = WScript.Arguments
'The first parameter begins with 0 as index.
Dim MacroName
MacroName = Arg(0) 'Ex : Macro_RSI_V10_4.10000442896544.xlsm
'create the excel object
Set objExcel = CreateObject("Excel.Application")
'view the excel program and file, set to false to hide the whole process
objExcel.Visible = False
'open an excel file (make sure to verify the location) .xls for 2003 or earlier
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\myUserName\Documents\BatForRundeck\" & MacroName)
'close the workbook
'objWorkbook.Close
'exit the excel program
objExcel.Quit
'release objects
Set objExcel = Nothing
Set objWorkbook = Nothing
Communication between Rundeck and my PC is working fine. I manage to launch .bat which create Text files in .txt or .csv formats. But I can't start Excel.
The question I ask is whether there is some way to Rundeck special procedure to run an Excel file on my machine or another remote machine?
After installing Python in 64 bits and then Python in 32 bits, after using OpenPyXL, xlrd, Win32com, Pythoncom, my problem persisted. Especially since the scripts .bat or .vbs worked very well on my Windows machine and launched Excel as expected.
The message:
pywintypes.com-error: (-2147352567, 'An exception has occurred.', (0, None, None, None, None, 0, -2146788248), None)
which caught my attention to the fact that it is rather a problem of the COM objects.
The solution is to run DCOMCNFG (shortcut Win+R, type DCOMCNFG and then Enter), go to Component Services --> My Computer --> DCOM Config --> Microsoft Excel Application. Now access the Properties and modify the option value in the Identity tab to "The interactive user".
An easy solution is to use a python script to launch your file, take at this, you can create an inline python script (or call an external script) on your Rundeck job pointed to your windows machine. Of course, you need to install the python interpreter on your Windows machine.

How to save a csv file through an lotusscript agent

I have a lotusscript agent which needs to move the contents of a cell in excel sheet(a csv file) to another cell. Following is the piece of code:
Dim xlApp As Variant, xlwb As Variant, xlsheet As Variant
Set xlApp = CreateObject ( "Excel.Application" )
Set xlwb = xlApp.Workbooks.Open(StrFilePath) 'strFilePath is the path to csv file
Set xlsheet = xlwb.Worksheets(1)
'Logic to check necessary cells in the excel sheet goes here...
'Following two lines move the contents from (p,1) to (1,n)
xlsheet.cells(1,n).value = xlsheet.cells(p,1).value
xlsheet.cells(p,1).value = ""
Now the problem arises when I'm trying to save this csv file after moving the contents.
I have used the below line to save the file:
xlwb.SaveAs(StrFilePath)
This method does not return any error. Yet the file doesn't get saved.
Then I have also tried using the below line to save the file:
xlApp.activeworkbook.SaveAs(StrFilePath)
This method returns "Automation object error".
The file is not getting saved by either of the methods. At this point, the agent is not able to execute further.
The agent then needs to move this file from the path StrFilePath to another directory using the FileCopy statement. At this point, the agent throws the "Permission denied" error.
The file is present in a directory in the D disk drive on the server.
The agent also has been given "Allow restricted operations with full administration rights".
Could someone please let me know what is the correct way to save this csv file and how to provide the necessary permissions for the file to be saved?
Thanks!
Okay, so i was digging a little more deeper and found the solution for this.
The following line of code worked for me and the file got saved successfully.
xlApp.ActiveWorkBook.save
And then I just added the following lines for the cleanup...(this was not part of my question, but writing here just for the sake of completion)
xlApp.ActiveWorkBook.close
xlApp.quit
Set xlApp = Nothing
But I'm not sure why SaveAs did not work. Will post if I find the answer for this.

Interacting with Session 0 Out-Of-Process Excel Object in VBScript

I have a very simple VBA script that I am running on Windows Server 2012. It creates an Excel Object, writes to two cells, saves the sheet as a CSV, and closes the Workbook and the Application, and then quits the Excel Object.
This works on Server 2003 without any issues.
When I run the script on Server 2012 R2, the Excel Object Process continues running and has to be terminated manually through task manager.
As I understand, the Excel application is running in Session-0, preventing the object from being closed by the script running in the user session. Additionally, if I alter the script to create the file and save/close the object then re-open the Excel file, it is unable to write to the file as again, it's in Session-0.
When the script runs, it creates an error in the error log of:
Service Control Manager Event 2073: The Interactive Services Detection
service terminated with the following error: Incorrect function.
The script is as follows:
set fso = CreateObject("Scripting.FileSystemObject")
currDir = fso.GetParentFolderName(Wscript.ScriptFullName)
outputFile = currDir & "\ExcelTest.csv"
set objExcel = CreateObject("Excel.Application")
set ExcelWorkbook= objExcel.workbooks.add()
objExcel.application.visible = false
objExcel.application.displayalerts =false
set objExcelWorksheet = objExcel.worksheets(1)
objExcelWorksheet.Cells(1, 1).Value = "Foo"
objExcelWorksheet.Cells(1, 2).Value = "Bar"
ExcelWorkbook.saveas outputFile,23
ExcelWorkbook.close false
objExcel.application.quit
objExcel.quit
set objExcel = nothing
I am looking for either a way to force the Excel object to open in the User Session, or somehow be able to control/access that Excel object. The above code is a simplified snippet of a larger script which opens and closes multiple CSV files, and as such I do need the ability to access those Excel objects.
Caveats: I have no access or ability to change the registry, nor install any third-party applications. Security is tight as we are a HealthCare-related shop.

Open an Excel file in exclusive mode using VBScript

I have a simple question, but I've searched for this and couldn't find any helpful topics..
I'm working on a VBScript that opens an Excel file and modify a few stuff in it.. so I'm using this code:
Set objXLApp = CreateObject("Excel.Application")
objXLApp.Visible = False
objXLApp.DisplayAlerts = False
Set objXLWb = objXLApp.Workbooks.Open(FilePath)
Now, what I want to do is to open the Excel file using a way that locks the file and prevents the user from opening it while it's open by the script (until it's closed).
Update:
I think the problem is somehow related to the Excel instances, I tried to do the following (while the file is open by the script):
When I manually open the file (while it's open by the script) they're both become a single instance.
When I open any other Excel file they're both also become a single instance!!! And the original file (opened by the script) becomes visible!
Now this is weird because I'm using CreateObject("Excel.Application") and not GetObject(, "Excel.Application")
There is registry key HKEY_CLASSES_ROOT\Excel.Sheet.8\shell\Open\command on Win 7 Excel 2010 for me with default value "C:\Program Files\Microsoft Office\Office14\EXCEL.EXE" /dde. The command line /dde switch enables DDE (Dynamic Data Exchange mechanism - an ancient Win 3.0 interprocess communication method) that forces Excel to start in a single instance. I've tried to remove that switch and opened workbooks, but to no avail. BTW, if you don't have a permission to edit the registry, or you intend to distribute your script to someone who doesn't, that is not a way. Also have tried this answer, but it doesn't work for Win 7 Office 2010.
I've tested test.xlsm file with DDE enabled. When user opens a file, actually it is just reopened in existing instance that make it visible. If any changes has been already made by the script, then Excel alerts:
Anyway write-access is given for the user. After that when the script saves the file, another alert appears:
Some time ago I created a script that worked with Excel application, and encountered the same issue with Win 7 Excel 2010 as you are describing. I noticed that if there were several Excel application instances created with CreateObject() within script, then Excel file opened by user always used exactly the first created instance. I've solved the issue by creating two invisible instances of Excel application, let's say dummy and target. In outline the algorithm for a script is as follows:
Create dummy instance first, no need to add a workbook. After that the dummy instance is exposured an Excel file to be opened by user within it.
Create target instance.
Quit dummy instance.
Open target workbook, modify and save it.
Quit target instance.
Consider the below code that illustrates a possible way to implement what you need:
' target file path
sPath = "C:\Users\DELL\Desktop\test.xlsm"
' create dummy instance
Set oExcelAppDummy = CreateObject("Excel.Application")
' create target instance
Set oExcelApp = CreateObject("Excel.Application")
' quit dummy instance
oExcelAppDummy.Quit
' open target workbook
With oExcelApp
.Visible = False
.DisplayAlerts = False
Set oWB = .Workbooks.Open(sPath)
End With
' make some changes and save
Set oWS = oWB.Sheets(1)
oWS.Cells(1, 1).Value = Now()
oWB.Save
' give additional time for test
MsgBox "Try to open test.xlsm, OK to end the script"
' close target workbook
oWB.Close
' quit target instance
oExcelApp.Quit
Trying open the file you will get desired output:
And the notification after the script ends:
That is strange that you aren't getting a message as below:
One possible method would be
to change the file attributes at the start and end of the code, the version below makes the file readonly and hidden
make your changes
save the file with a different name
change the attributes back
rename the changed file to the original name
code
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objXLApp = CreateObject("Excel.Application")
filePath = "C:\Temp\MyFile.xlsm"
filePath2 = "C:\Temp\MyFile1.xlsm"
set objFile = objFSO.GetFile(filePath)
objFile.Attributes = 3
objXLApp.Visible = False
objXLApp.DisplayAlerts = False
Set objxlWB = objXLApp.Workbooks.Open(filePath)
'do stuff
objxlWB.saveas filePath2
objxlWB.Close
objXLApp.Quit
set objXLApp = Nothing
objFile.Attributes = 32
objFile.Delete
objFSO.MoveFile filePath2, filePath

Refresh Excel using SSIS script task

I have an Excel file that gets external data from database table. I need to refresh the file automatically and email it. I intend to use SSIS script task to run some VB script that would open the file, refresh data, save and close (obviously without bringing up the application). then I'll use email task to send the file by email. All I need is the script that refreshes the file and being total noob in VB or C# I have to ask if anyone has a script that does that lying around and which I could customize for my file and use in my script task.
I'll appreciate any hints!
thanks a lot,
Vlad
Hope this is what you looking for
' Create an Excel instance
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
' Disable Excel UI elements
oExcel.Visible = True
oExcel.DisplayAlerts = False
oExcel.AskToUpdateLinks = False
oExcel.AlertBeforeOverwriting = False
Set oWorkbook = oExcel.Workbooks.Open("absolute path to your file")
oWorkbook.RefreshAll
oWorkbook.Save
oExcel.Quit
Set oWorkbook = Nothing
Set oExcel = Nothing
In my case (Connection to MS SQL DB), I had to uncheck the "enable background refresh" option for working fine.
Excel: Data > Connections > Properties > (uncheck) enable background refresh
Old post but 4M01 answer has helped me out heaps.
In my case I had to put a sleep just after opening the workbook to ensure the file loads correctly.
i.e.
oWorkbook = oExcel.Workbooks.Open("absolute path to your file")
Threading.Thread.Sleep(3000)
oWorkbook.RefreshAll
Note also in VS 2015 set is no longer required. so just remove "set " for the code to work.
This may not exactly fit your needs, but if it helps you or someone I was able to just use a simple
Execute Process Task
with the
Executable as /..path../Excel.exe and the
Arguments as the desired file (full path) to be opened

Resources