3

我尝试使用此代码创建一个 Excel 工作表。

Set ExcelObject = CreateObject("Excel.Application")

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

但我想要生成不止一个 excel 所以我尝试了这段代码-

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"

但它不起作用。请帮忙!

4

2 回答 2

2

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
于 2013-02-15T07:40:50.983 回答
0

可能想研究使用集合。在上面的示例中,您正在使用---当您创建它时,ExcelObject(x).visible = True 您真的还没有创建 5 。ExcelObjects

有几种方法可以做到这一点。但是,当您添加工作簿时,会玩弄您所拥有的东西。您正在将工作簿实例创建到工作簿集合中。因此,而不是将其引用为ExcelObject(x) => 您需要从项目中引用工作簿

ExcelObject.WorkBooks.item(x)

于 2013-02-15T07:42:22.217 回答