I need to add an Excel sheet at the end of the current sheet number 3. When I run the below program, however, I get a sheet at the first position. How can I resolve this?
The program basically copies data from one Excel workbook to another workbook, consisting of multiple sheets.
Code:
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
You can add sheets in the
After
position, ie this code adds the sheet after the last worksheet (provided byobjWrkBk.Sheets(objWrkBk.Sheets.Count))
whereobjWrkBk.Sheets.Count)
is the number of sheets prior to the addition.seems Worksheets property is read-only
https://msdn.microsoft.com/en-us/library/office/ff835542(v=office.15).aspx
whereas Sheets is the real thing where you can also add Sheets dynamically
https://msdn.microsoft.com/en-us/library/office/ff193217(v=office.15).aspx