I have a Master script which calls different actions (from different locations). I would like to write certain log messages during execution of this Master script. I have implemented a scripting object and a text file as
Set fso = CreateObject("Scripting.FileSystemObject")
Set write_log =fso.CreateTextFile("C:\ExecutionLog.txt",true)
...
write_log.WriteLine("Execution Step 1 Completed)
Now, when a call is made to another (external) action, I am attempting to implement logging in the same file referenced above. I have tried the following, to no avail:
Set fso = CreateObject("Scripting.FileSystemObject")
Set write_log = fso.OpenTextFile("C:\ExecutionLog.txt", ForAppending, False)
...
write_log.WriteLine("Execution Step 10 Completed)
My question is how to write into the same file in different actions?
If "to no avail" means "can't write to file in use by another process", you'll have to (Append)Open-Write-Close the file for each 'action' (script started by .Run or .Exec?) or even each single logging.
Related
I am really new to VBScript. This is my code, which creates a text file and attaches an object to it:
Set objExcel = CreateObject("Scripting.FileSystemObject")
objExcel.CreateTextFile("C:\mine.txt")
How can I use the getObject(Pathname,[class]) function?
VBScript GetObject documentation can be found here. Here is a VBScript sample:
Set objExcelFile = GetObject("C:\Scripts\Test.xls")
WScript.Echo objExcelFile.Name
objExcelFile.Close
This code will get you the Excel Workbook object contained in C:\Scripts\Test.xls. You can use TypeName() to confirm that:
Set objExcelFile = GetObject("C:\Scripts\Test.xls")
WScript.Echo objExcelFile.Name
WScript.Echo TypeName(objExcelFile)
objExcelFile.Close
The output will be:
test.xls
Workbook
If the specified Excel workbook doesn't exist the script will return an error. If an instance of Excel is already running you can use this code to get a reference to it:
Set objExcel = GetObject( , "Excel.Application")
For Each objWorkbook In objExcel.Workbooks
WScript.Echo objWorkbook.Name
Next
objExcel.Quit
Notice the comma before 'Excel.Application'. The script gets a reference to a running Excel application, lists open workbooks names and quits Excel. If there is no Excel instance running you will receive an error. This is also why you couldn't use GetObject() to get an instance of Scripting.FileSystemObject - there was no running instance.
You could use GetObject if there is an instance og Scripting.FileSystemObject already running in memory. Try this code:
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFso1 = GetObject("", "Scripting.FileSystemObject")
WScript.Echo TypeName(objFso)
WScript.Echo TypeName(objFso1)
You can see that you first need to use CreateObject() to and when FileSystemObject is running it is possible to get a reference to it, but this doesn't make much sense because you already have a reference to it (objFso). So, use CreateObject() to create an instance of FileSystemObject.
Note, that also GetObject() accepts the following monikers in argument:
"iis:<metabasepath>" - Allows a programmer to view and alter key IIS functionality for any webserver physically connected to this machine.
"java:<classname>" - Returns a reference to an unregistered java object found in the %system root%\java\trustlib folder using the Java Virtual Machine.
"script:<absolutepath>" - Returns a reference to an unregistered Windows Scripting Component or other supported script type.
"clsid:<clsid>" - Returns a reference to an object by it's class ID in the registry.
"WinMgmts:<string>" - Allows access to base Windows OS functionality with WMI.
"OBJREF:<base64encodedstring>" - Returns access to a running object instance.
"queue:<clsid/progid>" - Used to activate a queued COM+ component via MSMQ.
"new:<clsid/progid>" - Allows instancing of any COM component supporting the IClassFactory pointer (including queued components).
source: http://web.archive.org/web/20021001133221/http://www.aspemporium.com/aspEmporium/tutorials/GetObject/index.asp
I want to execute a VB script from Spring Boot application, the script is like:
' Creating a file as test acces to macro
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CreateTextFile("C:\excel\FLAG_TEST")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\excel\excelFile.xls")
objExcel.Application.EnableEvents = False
objExcel.Application.DisplayAlerts = False
objExcel.Application.Run "excelFile.xls!executeMacroFunction"
objExcel.Application.Quit
I tried to execute the script from Spring Boot service by:
Runtime.getRuntime().exec(new String[]{"C:\\Windows\\System32\\wscript.exe", "C:/vb/script.vbs"});
The above line code does not work on the application deployed on Tomcat 9 (it works fine when running as Spring Boot App on Eclipse)
Then I tried to execute the script via a batch file launched from the app
On batch file, I tried to execute the VB script by
rem First way
Set wscript = CreateObject("WScript.Shell")
wscript.Run "C:/vb/script.vbs"
--------------------
rem Second way (System 64bit)
C:\Windows\System32\wscript.exe C:/vb/script.vbs
--------------------
rem Third way (System 64bit)
wscript C:/vb/script.vbs
And running the batch file from Java with different ways too:
// First way
ProcessBuilder processBuilder = new ProcessBuilder("C:/batch/executor.bat");
final Process process = processBuilder.start();
// Second way
Process process = Runtime.getRuntime().exec("cmd /c start \"\" C:/batch/executor.bat");
// Third way
Process process = Runtime.getRuntime().exec(
"cmd /c start \"\" C:/batch/executor.bat",
null,
new File("C:\\Windows\\SysWOW64"));
All these ways do not work, the scripts have no problem since they work when I run manually the batch file (by double click)
On the execution of the macro from Spring Boot, the test file (FLAG_TEST) is created and then the execution is blocked at the line:
Set objExcel = CreateObject("Excel.Application")
Am I missing something ?...Thanks a lot in advance !
Tried also with Jacob DLL to run the Macro inside the excel file, it also didn't work for me within a Tomcat server
I decided at the end to abandon any kind of external tool and do the thing within Spring Boot, parsing the Excel file via an Excel Java API and migrating the Macro program to Java: JExcel
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
Unlike some other Excel parsing APIs, the Jexcel get the cell text as it is: String, Number, Boolean, Formula (its displayed result), no need to handle the different cases of content type
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.WorkbookSettings;
// Set Encoding 1252 that supports many European languages (special characters included)
WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setEncoding("Cp1252");
Workbook workbook = Workbook.getWorkbook(new File(EXCEL_FILE_LOCATION), workbookSettings);
Sheet sheet = workbook.getSheet(0);
Cell cellDemo = sheet.getCell(0, 0); // Or sheet.getCell("A1");
// Get the displayed cell centent as a text
String cellContent = cellDemo.getContents();
System.out.print("Cell A1 centent:" + cellContent);
The Java parsing makes the exception handling of data validation easier and more precise, no kind of abstract HMI error message (Error occurred wile processing the Excel file...)
Turns out that the Excel Java reading API implementation took less time than the several attempts of runing the Macro externally :D
I would like to automate the opening of a pdf which is defined using a dynamic hyperlink, but using the DEFAULT pdf editor of the user, but cannot fathom how to do this beyond the code below which opens the file in
I have other code to save the pdf which automatically saves it and opens a file in the default program for each user. But I don't know how to do the reverse and have a file which is searched for and found via the dynamic hyperlink - which will then allow them to update.
This is to shortcut sometone opening various folders, manually seatching, then opening up a file. ideally Id want to automate.
Here is the code I have so far which works but will only open in Adobe and not the default program - is this perhaps a setting thing on my PC or is it code which is missing?
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("TNR Report")
Dim r As Range: Set r = ws.Range("A82") ' this defines the actual path and filename to be searched for
Dim strHyperlink As String
On Error GoTo CannotFindFile
strHyperlink = r.Value
ThisWorkbook.FollowHyperlink strHyperlink
File needs to open with nuance to enable the user to edit and update the "record", but opens only in reader which is no use and kind of defeats the purpose of the code.
2 possibilities:
Make Nuance your default application in Windows to open PDF files.
Use a shell command to start nuance with a filename as parameter
Shell """C:\Path To Nuance\Nuance.exe"" ""C:\Path To PDF\pdffile.pdf"""
I'm currently working on simplifying a process at work. It involves a Chatillon DFIS Force Meter which uses a serial connection to transmit data. The data gets sent to the Chattillon program as text and can only be saved as a .dat file. I'm trying to set up an Excel workbook that can just automatically open the program and have different commands to put the information straight into Excel. The Commands would involve changing the units, zeroing the sensor, and transmitting.
I've done some looking around and found that the Shell feature gives you access to opening the file and should help allow you to control it but I haven't found a way to call and manipulate the program through Excel.
Chatillon Program, basically buttons to click with a mouse
Excel and VBA can control external applications if they have a COM interface - that is to say, if you can declare the application as an object, create an instance of the object, and see its methods and attributes.
If you can possibly get hold of a COM wrapper for your program, do it that way.
If you can't... You won't enjoy doing it using I/O streams and a Windows Shell object, because command-line DOS interfaces aren't particularly friendly as a User Interface, and they are flakier than breakdancing in a pastry factory when you try to use them as an API in VBA.
Firstly, you need the 'WshShell' object exposed by the Windows Script Host Object Model. You can declare and instantiate it by late binding as shown:
Dim objWshell As Object
Set objWshell = CreateObject("WScript.Shell")
But the correct method (which will give you Intellisense drop-downs of the properties and methods) is to use the 'Tools:References...' dialog to create a reference to the parent library, which is usually found at C:\Windows\System32\wshom.ocx
You can then declare the Shell object as:
Dim objWshell As IWshRuntimeLibrary.WshShell
Set objWshell = New IWshRuntimeLibrary.WshShell
Running a command-line executable and reading the I/O streams in VBA:
This is an example that opens a command window and runs a command-line executable, feeding it a command-line switch '-s' and a parameter encapsulated in double quotes.
Note that the executable I'm running is NOT 'regsvr32.exe' - my shell object is executing cmd.exe, and that is the source and sink of the I/O streams.
You can, of course, run your application directly. It might work. But it is very common for the output stream to lock or 'hang' your calling function and its VBA thread when you call .StdOut.ReadLine or .StdOut.ReadAll - you have been warned.
With objWshell.Exec("CMD /K")
.StdIn.WriteBlankLines 3
.StdIn.WriteLine "C:"
.StdIn.WriteLine "CD C:\"
.StdIn.WriteLine "regsvr32.exe -s " & Chr(34) & "%LIBDIR%\FXPricer.dll" & Chr(34)
.StdIn.WriteBlankLines 1
Do Until .StdOut.AtEndOfStream
Debug.Print .StdOut.ReadLine
Loop
Do Until .StdErr.AtEndOfStream
Debug.Print .StdOut.ReadLine
Loop
.Terminate
End With
Share and Enjoy. And, as always, watch out for line breaks inserted by your browser (or by StackOverflow's textbox interface) in the source code samples.
What I want to do is more complex than selecting a file from a list of files. I will start in a directory, then I want to change to the most recently modified directory. I then want to repeat that process in a sub-directory, and then, inside of that, I want to select the most recently modified excel file and open it.
What is the best approach to do this?
What objects / methods should I be looking into?
The simplest function is
FileDateTime(pathname)
where pathname can be a directory for folder.
Alternatively, you can use the FileSystemObject object, DateLastModified property:
Dim fileModDate As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(<filenamestringhere>)
fileModDate = f.DateLastModified
All of the above can be explored in VBA help.