Hi i am trying to convert .xlsx file to .csv file and then read this csv file in python. Below is my code in VBS:
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.Close False
oExcel.Quit
WScript.Echo "Done"
This code is working properly. but when i read converted csv file in python the numbers get converted to string. example:
$ 266,74245.4545 -> '$266,74245'
Is there any way i can make changes in vbs code to get these numbers as it is in csv file. for my application i require whole number while reading.
I took above code from "https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-command-line"
I found solution to this question. I'm changing the currency($) format to a Numbers format in the opened worksheet, and then converting it to CSV.
This how the code looks:
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.ActiveSheet.Range(WScript.Arguments.Item(2)).Select
oExcel.Selection.NumberFormat = "0000000000.00000"
oBook.SaveAs WScript.Arguments.Item(1), 6
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 was asked to look for a procedure that convert an Excel file into a CSV one, however I have no knowledge on .bat. I've seen some people doing so with some commands and I would like to know if I can do the same but important: skipping the first five rows of the file.
I would appreciate any help you give me.
A very easy way, is to create a vbs script. Paste the below into a notepad and save as XlsToCsv.vbs. Make sure you give the full path of sourcexlsFile and also destinationcsvfile
To use: XlsToCsv.vbs [sourcexlsFile].xls [destinationcsvfile].csv
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.Sheets(1).Range("1:5").EntireRow.Delete 'this removes the first five rows everytime
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
I have VBscript code which opens XLS file and export it to CSV, see below:
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open("test.xls")
oBook.SaveAs "test.csv", 6
oBook.Close False
oExcel.Quit
It works fine but I need to do the same - convert XLS to CSV with already opened file "test.xls" on my computer which is different (edited by me) versus saved version. Is that possible?
Yes, you just need to connect the existing instance of Excel and set workbook object variable equal to the already open workbook instead:
Set oExcel = GetObject(, "Excel.Application")
Set oBook = oExcel.Workbooks("test.xls")
I am using the following VBS script found on stackoverflow to convert xls to csv. It works fine. I want to run it with the batch file at the bottom. I don't know how to achieve what I want. The batch file gives the csv file the same name as the xls file. Because the xls file has two worksheets in it I need to produce two csv's for each xls file
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
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(1))
oBook.SaveAs WScript.Arguments.Item(2), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
Here's the batch file
FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%i.csv"
I need to pass in 2 output .csv file names one should be nnnnn_1.csv the other should be nnnnn_2.csv to account for the 2 worksheets in the xls files.
Thanks for any help
Similarly to Scott's answer above, I would probably change the script to work this way, since this change will just work for all sheets in a given workbook and output each to a .csv file without worrying if there are 1, 2 or 10 sheets.
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))
Dim oNewBook
shIndex = 1 ' start with 1
For shIndex = 1 To oBook.Worksheets.Count
oBook.Worksheets(shIndex).Copy
Set oNewBook = oExcel.ActiveWorkbook
oNewBook.SaveAs Replace(WScript.Arguments.Item(1),".csv","_" & shIndex & ".csv"), 6
oNewBook.Close False
Next
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
This script will save every worksheet in the workbook as [cvs base name] - [worksheet name].csv.
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 BaseName, oExcel, oBook, xlWorksheet, i
BaseName = Replace( WScript.Arguments.Item(0), ".cvs", "")
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(WScript.Arguments.Item(0))
For Each xlWorksheet In oBook.Worksheets
xlWorksheet.Copy
oExcel.ActiveWorkbook.SaveAs BaseName & " - " & xlWorksheet.Name & ".csv"
oExcel.ActiveWorkbook.Close False
Next
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
If you change the VBS script to this it should work:
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.Worksheets(1).Copy
Dim oBookNew1
Set oBookNew1 = oExcel.ActiveWorkbook
oBookNew1.SaveAs Replace(WScript.Arguments.Item(1),".csv","_1.csv"), 6
oBookNew1.Close False
oBook.Worksheets(2).Copy
Dim oBookNew1
Set oBookNew1 = oExcel.ActiveWorkbook
oBookNew2.SaveAs Replace(WScript.Arguments.Item(1),".csv","_2.csv"), 6
oBookNew2.Close False
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
I have written an alternative solution in Python that exports the present excel sheets of a workbook in CVS format.
You can find it here
Best,
Julian