VBScript overwrite file - vbscript

I'm using the following script to convert an Excel file into a CSV tab delimited txt file.
xls = "C:\Ristken Data Load\Wade SPIFF log file"
csv = "c:\Ristken Data Load\Wade SPIFF log file"
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(xls)
oBook.Worksheets(2).Activate
oBook.Worksheets(2).Rows("1:4").Delete
oBook.SaveAs csv, -4158
oBook.Close True
oExcel.Quit
I'd like to add something to this script so that, it overwrites the txt file each time it runs without having the popup box asking if you want to overwrite the existing file.

Easier then I thought it would be.
xls = "C:\Ristken Data Load\Wade SPIFF log file"
csv = "c:\Ristken Data Load\Wade SPIFF log file"
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(xls)
oBook.Application.DisplayAlerts = False
oBook.Worksheets(2).Activate
oBook.Worksheets(2).Rows("1:4").Delete
oBook.SaveAs csv, -4158
oBook.Close True
oExcel.Quit

Related

It is necessary to write a vbs script to run multiple xlam files in one excel instance

The task is to write vbs scripts that:
The first vbs script (1.vbs) opens an excel instance and loads the 1.xlam file into the open excel instance.
The second vbs script (2.vbs) loads the 2.xlam file into the same excel instance.
The next one (3.vbs) loads the same instance of excel 3.xlam and so on.
I tried a lot, but I have new *.xlam being loaded into new instances of excel, not the previously opened one.
How to solve a problem?
My loader1.vbs - for load loader1.xlsm
Set omExcel = CreateObject("excel.application")
omExcel.Visible = True
vmAlertXLSM = omExcel.AutomationSecurity
omFile.AutomationSecurity = 1
vmFile = replace(WScript.ScriptFullName, ".vbs",".xlsm")
omExcel.Workbooks.Open vmFile
omExcel.AutomationSecurity = vmAlertXLSM
This Ok
I need to write loader2.vbs which loads my loader2.xlsm to the same Excel instance so that the functions written in loader1.xlsm and loader2.xlsm can see each other
It doesn't work like that - a new instance of Excel opens:
vmFile = replace(WScript.ScriptFullName, ".vbs",".xlsm")
With GetObject(, "Excel.Application")
.Visible = True
.Workbooks.Open (vmFile)
End With
Excel Instances
You can open a file in a new instance of Excel with:
With CreateObject("Excel.Application")
.Visible = True
.Workbooks.Open ("C:\Test1.xlsx")
End With
You can open another file in a running instance with:
With GetObject(, "Excel.Application")
.Workbooks.Open ("C:\Test2.xlsx")
' Prove that your in the same instance:
ReDim wbNames(.Workbooks.Count - 1)
For Each wb In .Workbooks
wbNames(n) = wb.FullName
n = n + 1
Next
MsgBox "Open Workbooks: " & vbLf & vbLf & Join(wbNames, vbLf)
End With

Create ANSI text file using vbscript

I must create a text file with ANSI encoding using vbs.
If I just create it, without to write any text, using this code...
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFileTxt = objFSO.objFSO.CreateTextFile("filename.txt", True, False)
Set ObjFileTxt = nothing
Set objFSO = nothing
... I get an ANSI text file, but if I try to write some text, for example...
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ObjFileTxt = objFSO.CreateTextFile("filename.txt", True, False)
ObjFileTxt.Write "ok"
Set ObjFileTxt = nothing
Set objFSO = nothing
... I get an UTF8 text file.
Any help?
It's not possible that the code you posted would create a UTF8-encoded output file. The CreateTextFile method supports only ANSI (windows-1252) and Unicode (little endian UTF-16) encodings.
The only ways to create UTF8-encoded files in VBScript are the ADODB.Stream object:
Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 'text
stream.Position = 0
stream.Charset = "utf-8"
stream.WriteText "some text"
stream.SaveToFile "C:\path\to\your.txt", 2
stream.Close
or writing the individual bytes (including the BOM).
I know this is already old, but for future references...
Believe it or not, I had the same problem until I converted my VBS to ANSI (was UTF-8). Then, every new text file created with it was also ANSI and not UTF-8 any more.

Convert Excel workbook to CSV with user-provided filenames

First, I need to delete the top 4 rows from the sheet either before or after the conversion. There currently isn't anything in this script that will delete rows from the Excel file or from the CSV file that it creates.
Second, I'd prefer to pass the source and destination in this script rather then passing them later. Currently this script requires a command line to pass the source and destination it looks something like this.
C:\exceltocsv "source.xls" "destination.csv"
Instead of requiring source.xls and destination.csv to be provided as commandline arguments I'd rather have them resolved in the VBScript itself. Is this possible?
if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Worksheets(2).Activate
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
You can use the InputBox function to prompt for user input. Rows can be removed from an Excel worksheet via <range>.EntireRow.Delete.
Something like this should do what you want:
xls = InputBox("Enter source file.")
csv = InputBox("Enter destination file.")
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(xls)
oBook.Sheets(1).Range("1:4").EntireRow.Delete
oBook.SaveAs csv, 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
Edit: If you want hardcoded paths, simply define them as strings:
xls = "C:\path\to\input.xls"
csv = "C:\path\to\output.csv"
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(xls)
oBook.Sheets(1).Range("1:4").EntireRow.Delete
oBook.SaveAs csv, 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
Thanks to Ansgar Wiechers I was able to come up with this script
xls = "C:\[Path]"
csv = "c:\[Destination]"
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(xls)
oBook.Worksheets(2).Activate
oBook.Worksheets(2).Rows("1:4").Delete
oBook.SaveAs csv, 6
oBook.Close False
oExcel.Quit
And it runs like a champ in cmd. Thanks a million!
However, I went to implement this into my process and found out that SQL Server Agent has major issues in executing VBScripts.
cscript is the command that is suggested to execute the script, but it doesn't work. After more research I found that other people have had similar issues and they all suggest writing the script in VB.NET instead of VBScript. This way SSIS can process the script.
Ansgar I marked your response as the answer since it answered my question, but sadly it only lead me to a dead end with VBScript.

Converting Microsoft XML file format to Excel file

I have requirement that I'm not really sure on how to go about it. I have a file Doc.xml, this is in Microsoft XML format. I need to create a VB script that will change/convert the Doc.xml to Doc.xlsx, so when the user tries to open the file it will open as an Excel file.
One of the requirements is that this script will be run from the Windows Scheduler.
Any ideas or recommendation will be really appreciated.
This is the script I created and is working, but when I try to change the SaveAs extension to ".csv" the file is not being saved correctly. I guess I need to find out what the code is for saving in CSV.
Dim objXLApp, objXLWb, objXLWs
Set objXLApp = CreateObject("Excel.Application")
objXLApp.Visible = True
Set objXLWb = objXLApp.Workbooks.Open("C:\Users\jmejia\Desktop\XML_F\ZOOSHR_130622.xml")
'Do nothing with File, just open it to be save agains as a new file format
objXLWb.SaveAs "C:\Users\jmejia\Desktop\XML_F\ZOOSHR_130622.xlsx", 51
objXLWb.Close (False)
Set objXLWs = Nothing
Set objXLWb = Nothing
objXLApp.Quit
Set objXLApp = Nothing
If your file was created and exported from Excel > 2006? then it will have the tags in it such that double clicking in explorer on a windows machine with any Excel that supports xml format will automatically open it in Excel.
Your file is likely to start with something like:
<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
Const xlXLSX = 51
REM 51 = xlOpenXMLWorkbook (without macro's in 2007-2013, xlsx)
REM 52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2013, xlsm)
REM 50 = xlExcel12 (Excel Binary Workbook in 2007-2013 with or without macro's, xlsb)
REM 56 = xlExcel8 (97-2003 format in Excel 2007-2013, xls)
dim args
dim file
dim sFile
set args=wscript.arguments
dim wshell
Set wshell = CreateObject("WScript.Shell")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open( wshell.CurrentDirectory&"\"&args(0))
objExcel.DisplayAlerts = FALSE
objExcel.Visible = FALSE
objWorkbook.SaveAs wshell.CurrentDirectory&"\"&args(1), xlXLSX
objExcel.Quit
Wscript.Quit

OpentextFile Permission Denied Error

I'm getting an error when i use opentextfile. The problem is weird because it works for a few hundred files then pops up.
Basically the script gets a collection of files, searchs in them for a string which it then removes and writes back the modified content to the same file. The problem occurs when the script wants to open the file again so it can write the modified contents to it.
This is the code:
For Each objFile in colFiles
Set objCurrentFile = objFSO.OpenTextFile(objFile.Path, ForReading)
'Get file contents - exclude end tag '
Do Until objCurrentFile.AtEndOfStream
strLine = objCurrentFile.ReadLine
If InStr(strLine, strSearchTerm) = 0 Then
strNewContents = strNewContents & strLine & vbCrLf
End If
Loop
objCurrentFile.Close
objCurrentFile = nothing
'Write new file contents to existing file '
Set objNewFile = objFSO.OpenTextFile(objFile.Path, ForWriting) 'PROBLEM LINE '
objNewFile.Write strNewContents
objNewFile.Close
objNewFile = nothing
Next
The file is read-only.
Try adding this before you open the text file for writing. If the file is read-only it will remove the read-only attribute.
IsReadOnly = False
IF objFile.Attributes AND 1 Then
objFile.Attributes = objFile.Attributes - 1
IsReadOnly = True
End If
Then add this when you are done writing to the file. If the file was read-only set it back to read-only.
If IsReadOnly Then
objFile.Attributes = objFile.Attributes + 1
IsReadOnly= False
End If
I found the issue. I was opening the text file and then copying it to another folder and then performing more operations on the file before closing the stream.
Once i moved the copy file code to before i opened the stream it works perfectly.
Thanks for the help though, i'll use your code in the future to be safe when working with text files.
you can try givin total control permission to the folder where is the the file to read.

Resources