如何在所有现有Excel工作表之后添加工作表?

我需要在当前工作表编号3的末尾添加Excel工作表 . 但是,当我运行以下程序时,我会在第一个位置获得一个工作表 . 我该如何解决这个问题?

该程序基本上将数据从一个Excel工作簿复制到另一个工作簿,由多个工作表组成 .

码:

Dim objXL,objWrkBk,objWrkSht,a,n
Set objfso=CreateObject("Scripting.FileSystemObject")
Set objXL=CreateObject("Excel.Application")
Set objWrkBk=objXL.Workbooks.Open("C:\learning\demo.xlsx")
m=objWrkBk.Worksheets.count
msgbox m
For n=1 to m
Set objWrkBk=objXL.Workbooks.Open("C:\learning\demo.xlsx")
Set objWrkSht=objWrkBk.Worksheets("Sheet"&n)
columncount = objWrkSht.usedrange.columns.count
rowcount = objWrkSht.usedrange.rows.count
For i=1 to rowcount
For j=1 to columncount
If   objWrkSht.cells(i,j).value <> "" Then
    a= objWrkSht.cells(i,j).value& "   "
End If
'Next
'Next
check=objfso.FileExists("C:\learning\demo1.xlsx")
If not check Then
    objXL.Workbooks.Add
    objXL.ActiveWorkbook.SaveAs("C:\learning\demo1.xlsx")
End If
Set objWrkBk1=objXL.Workbooks.Open("C:\learning\demo1.xlsx")
If n<=3 Then
    Set objWrkSht1=objWrkBk1.Worksheets("Sheet"&n)
End If
If n>3 Then
    objXL.Worksheets.add
    Set objWrkSht1=objWrkBk1.Worksheets("Sheet"&n)
End If

If   objWrkSht.cells(i,j).value <> "" Then
objWrkSht1.cells(i,j).value=a
objWrkBk1.Save
End If
Next
Next
Set objWrkSht=Nothing
Set objWrkBk=Nothing
Set objWrkSht1=Nothing
Set objWrkBk1=Nothing

Next
objXL.Quit
Set objXL=Nothing

回答(2)

2 years ago

您可以在 After 位置添加工作表,即此代码在最后一个工作表之后添加工作表(由 objWrkBk.Sheets(objWrkBk.Sheets.Count)) 提供,其中 objWrkBk.Sheets.Count) 是添加之前的工作表数 .

Set objXL = CreateObject("Excel.Application")
Set objWrkBk = objXL.Workbooks.Add
Set objWrkSht = objWrkBk.Sheets.Add(, objWrkBk.Sheets(objWrkBk.Sheets.Count))

2 years ago

似乎Worksheets属性是只读的

返回表示指定工作簿中所有工作表的Sheets集合 . 只读表格对象 .

https://msdn.microsoft.com/en-us/library/office/ff835542(v=office.15).aspx

而Sheets是真实的东西,你也可以动态添加表格

指定或活动工作簿中所有工作表的集合 .

https://msdn.microsoft.com/en-us/library/office/ff193217(v=office.15).aspx