Monday, March 23, 2009

VB Script to get the Tab names of the excel workbook

Have you ever wanted to get all the tab names in an excel workbook. I had an experience, i wanted to confirm i have included checklist for all the functionality in the current build, i had 34 tabs in the workbook, and i couldn't find any excel functions for that so created this script

'Create excel object
Set objExcel = CreateObject("Excel.Application")
' Open the excel sheet with the object, providing the file path
Set objWorkbook = objExcel.Workbooks.Open ("C:\MyFolder\Summary of Test Scripts.xlsx")
'Find the count of excelsheets and iterate through the worksheet and find the name 'and store ina variable

for i=1 to objExcel.activeworkbook.sheets.count
mystr=objExcel.activeworkbook.sheets(i).name
mystr1= mystr1 + trim(mystr) + vbcrlf
'msgbox i & " " & mystr
Next

objExcel.Quit
Set objExcel =NOTHING
Set objWorkbook =NOTHING
'create filesystem object to write to a text file
Set myFSO = CreateObject("Scripting.FileSystemObject")
'open textfile, provide the name
Set WriteStr = myFSO.OpenTextFile("Tabname.txt", 8, True)
'write the info to the file
WriteStr.WriteLine mystr1
WriteStr.Close
'close all the objects created
SET WriteStuff = NOTHING
SET myFSO = NOTHING

wscript.echo "Done"

This article can be found at the blog section of my personal site www.dileepk.info

No comments: