excel - .Copy()两次

时间:2014-05-22 02:18:54

标签: vb.net excel

我有一个包含6个工作表的工作簿。我想保存表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

第二次复制时,我的应用程序崩溃并返回此错误:索引无效。 (来自HRESULT的异常:0x8002000B(DISP_E_BADINDEX))。我注意到错误是由于第二次尝试“复制”,所以在这种情况下如何复制两次?

2 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

不确定原因,但在这种情况下.Worksheets(2).Copy()会打开另一个工作簿“Book2”,因此需要关闭它。

.DisplayAlerts = False
.ActiveWorkbook().Close()

关闭复制的工作表后,再次复制。

.Worksheets(3).Copy()
filename = "2.txt"
.ActiveWorkbook.SaveAs(filename, -4158)

完整的代码将是

.Worksheets(2).Copy()
filename = "1.txt"
.ActiveWorkbook.SaveAs(filename, -4158)
.DisplayAlerts = False
.ActiveWorkbook().Close()
.Worksheets(3).Copy()
filename = "2.txt"
.ActiveWorkbook.SaveAs(filename, -4158)