# Excel – Run excel macros (vba) from vbscript file

microsoft excelvbavbscript

I have a vbs file that pulls information from my database and exports the data to an Excel file (C:\file.csv). Once this is done, I run a series of macros (vba) to format this data. These macros are always the same, I normally copy/paste them over from a text file into the spreadsheet and then manually run them.

Is there a way I can include the macro vba to the vbs file so, after the data is exported to the spreadsheet, the macros run? Similar solutions show how to call a pre-defined macro in an Excel file, where I want the contents of the macro to be saved/executed in/from my vbs file. This will be helpful since the vbs is creating a brand new file, then would run formatting macros.

My thought is I'll need to use Set objWorkbook = objExcel.Workbooks.Open("C:\file.csv")

You are on the right track. What you need first is to set up a new variable for the Excel.Application using late binding. It's under that object where all the normal excel VBA goodies hide. Below is an example vbs script that will open a new workbook, add a new sheet, name it "TEST", and add some content into cell A1 of that new sheet. When it's done, vbs will echo "Finished"

Sub createWB()

'Set the excel application variable
set xlApp = CreateObject("Excel.Application")

'Make it visible, or hide it in the background
xlApp.Application.Visible = true

'Open a new workbook, for instance
xlWB.Activate

'Add a sheet, name it test, bring it front and center
xlSheet.Name = "TEST"
xlSheet.Activate

'Put something in cell A1
xlSheet.Cells(1,1).value = "TEST CELL CONTENT"

End Sub

'Call the subroutine above
call createWB

WScript.Echo "Finished."
WScript.Quit


You may have to monkey around a bit with your existing VBA code to make vbs happy, but you'll find that writing your macros in vbs, is just as functional as writing them in vba.