I have a workbook that consists of 6 worksheets. I want to save sheet 2 & 3
With Excel
.SheetsInNewWorkbook = 6
.Workbooks.Add()
....
.Worksheets(2).Copy()
filename = "1.txt"
.ActiveWorkbook.SaveAs(filename, -4158)
.Worksheets(3).Copy()
filename = "2.txt"
.ActiveWorkbook.SaveAs(filename, -4158)
End With
Upon copying the 2nd time, my application crash and return this error: Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX)). I noticed the error was due to trying to "Copy" the 2nd time, so how should I copy twice in this case?
Try this:
With Excel
Dim sourceWB As Workbook = .Workbooks.Add()
'~~> Rest of your code here
.
.
.
sourceWB.Worksheets(2).Copy
.ActiveWorkbook.SaveAs("C:\blah\test1.txt", -4158)
sourceWB.Worksheets(3).Copy
.ActiveWorkbook.SaveAs("C:\blah\test2.txt", -4158)
End With
Not sure why, but .Worksheets(2).Copy()
will open another workbook "Book2" in this case, therefore need to close it.
.DisplayAlerts = False
.ActiveWorkbook().Close()
Upon closing the copied worksheet then copy again.
.Worksheets(3).Copy()
filename = "2.txt"
.ActiveWorkbook.SaveAs(filename, -4158)
The full code will be
.Worksheets(2).Copy()
filename = "1.txt"
.ActiveWorkbook.SaveAs(filename, -4158)
.DisplayAlerts = False
.ActiveWorkbook().Close()
.Worksheets(3).Copy()
filename = "2.txt"
.ActiveWorkbook.SaveAs(filename, -4158)
User contributions licensed under CC BY-SA 3.0