Vaibhav Warpe
Vaibhav Warpe

Reputation: 141

Open, Update and Save Excel workbook automatically

I want to modify the column's number format automatically in excel.

Set excel = CreateObject("Excel.Application")
Set oWB = excel.Workbooks.Open("E:\Docs\Invoice.csv")

/* Excel Macro starts */
Columns("G:G").Select
Selection.NumberFormat = "m/d/yyyy"
Columns("H:H").Select
Selection.NumberFormat = "0.00"
/* Excel Macro ends */

oWB.save
oWB.Application.Quit

I run this .vbs using command line. Excel doc does not get updated.
Could anyone please help me in resolving this issue ?

Thanks in advance

Upvotes: 4

Views: 62338

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149287

What you are missing in the above code is you are not fully qualifying the Excel Objects.

How would vbs understand what is Columns("G:G")?

Try this

Dim objXLApp, objXLWb, objXLWs

Set objXLApp = CreateObject("Excel.Application")
Set objXLWb = objXLApp.Workbooks.Open("E:\Docs\Invoice.csv")

'~~> Working with Sheet1
Set objXLWs = objXLWb.Sheets(1)

With objXLWs
    '/* Excel Macro starts */
    .Columns("G:G").NumberFormat = "m/d/yyyy"
    .Columns("H:H").NumberFormat = "0.00"
    '/* Excel Macro ends */
End With

objXLWb.Save
objXLWb.Close (False)

Set objXLWs = Nothing   
Set objXLWb = Nothing

objXLApp.Quit
Set objXLApp = Nothing

EDIT: My Only concern is that the numberformat will not stay as it is a CSV file. You might want to save it as an Excel file?

CODE

Dim objXLApp, objXLWb, objXLWs

Set objXLApp = CreateObject("Excel.Application")

objXLApp.Visible = True

Set objXLWb = objXLApp.Workbooks.Open("E:\Docs\Invoice.csv")

'~~> Working with Sheet1
Set objXLWs = objXLWb.Sheets(1)

With objXLWs
    .Columns("G:G").NumberFormat = "m/d/yyyy"
    .Columns("H:H").NumberFormat = "0.00"
End With

'~~> Save as Excel File (xls) to retain format
objXLWb.SaveAs "C:\Sample.xls", 56

'~~> File Formats
'51 = xlOpenXMLWorkbook (without macro's in 2007-2010, xlsx)
'52 = xlOpenXMLWorkbookMacroEnabled (with or without macro's in 2007-2010, xlsm)
'50 = xlExcel12 (Excel Binary Workbook in 2007-2010 with or without macro's, xlsb)
'56 = xlExcel8 (97-2003 format in Excel 2007-2010, xls)

objXLWb.Close (False)

Set objXLWs = Nothing
Set objXLWb = Nothing

objXLApp.Quit
Set objXLApp = Nothing

Upvotes: 7

Related Questions