Home » excel » vbscript – Generating more than one excel

vbscript – Generating more than one excel

Posted by: admin April 23, 2020 Leave a comment

Questions:

I tried this code to create an excel sheet.

Set ExcelObject = CreateObject("Excel.Application")

ExcelObject.visible = True
ExcelObject.WorkBooks.Add       
ExcelObject.Sheets(1).Cells(1,1).value = "My first excel" 

But i want more than one excel to be generated So i tried this code-

Set ExcelObject = CreateObject("Excel.Application")

For x= 1 to 5
ExcelObject(x).visible = True
ExcelObject(x).WorkBooks.Add 'Adds a workbook to an excel object
x=x+1   
ExcelObject.Sheets(1).Cells(1,1).value = "My first excel"

But it is not working.Please help!

How to&Answers:

Your code has some errors:

  1. You missed Next x

  2. You don’t have to increment x since you use For..Next statement. Next x will do that for you.

Working code:

For VB.NET:

Dim ExcelObject() As Object
ExcelObject = New Object(5) {}
For x = 1 To 5
    ExcelObject(x) = CreateObject("Excel.Application")
    ExcelObject(x).visible = True
    ExcelObject(x).WorkBooks.Add() 'Adds a workbook to an excel object
    ExcelObject(x).Sheets(1).Cells(1, 1).value = "My first excel"
Next x

For VBScript:

Dim ExcelObject(5) 
For x = 1 To 5
    Set ExcelObject(x) = CreateObject("Excel.Application")
    ExcelObject(x).visible = True
    ExcelObject(x).WorkBooks.Add() 'Adds a workbook to an excel object
    ExcelObject(x).Sheets(1).Cells(1, 1).value = "My first excel"
Next

Answer:

May want to look into using collections. In the above example where you’re using ExcelObject(x).visible = True — You really haven’t created 5 ExcelObjects yet when you created it.

There are several ways to accomplish this. But playing off what you have when you add a workbook. You’re creating instances of workbooks into your workbooks collection. So rather then reference it as ExcelObject(x) => you’ll need to reference the workbooks from the items

ExcelObject.WorkBooks.item(x)