如果在下一次迭代中使用同一文件,则尝试使Excel文件保持循环打开状态时出现VB.Net错误

时间:2019-02-04 19:50:24

标签: c# excel vb.net

我在VB.net中有一个程序,可以从datagridview中的项目生成PDF文件。它遍历datagridview,确定文件的类型,打开文件,保存PDF,然后关闭文件。通常,这些列表使用同一Excel文件中的多个工作表,每个工作表在datagridview中都有其自己的条目。为了防止sub连续打开和关闭同一个Excel文件20次,如果列表中的下一个项目是同一个文件,我试图使该文件保持打开状态。

这是问题所在。如果列表中的Excel文件与第一个文件不同,则出现此错误:

System.Runtime.InteropServices.COMException: 'Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

在此行:

xl.Workbooks(WorkbookName).Sheets(CurrentSheet).ExportAsFixedFormat(0, FileName:=ReportPath & "\" & PDFName)

这是完整的代码(为提高效率已删除了不相关的行):

Sub PrepareForPDF()
    Dim xl As Object
    Dim DocPath As String
    Dim ReportPath As String
    Dim CurrentFile As String
    Dim CurrentBook As Excel.Workbook
    Dim CurrentSheet As String
    Dim PDFName As String
    Dim WorkbookName As String
    Dim WbOpen As Boolean = False

    DocPath = Form1.txtSourcePath.Text.ToString
    ReportPath = Form1.txtSavePath.Text.ToString

'Loop through DGV, generate a PDF of each file
    For i As Integer = 0 To Form1.DataGridView1.Rows.Count - 1

        CurrentFile = DocPath & "\" & Form1.DataGridView1(1, i).Value.ToString

        'Build the PDF file name
        PDFName = Form1.DataGridView1(0, i).Value.ToString & " - " & Form1.DataGridView1(1, i).Value.ToString
        If Form1.DataGridView1(2, i).Value.ToString = "Excel" Then
            PDFName += " - " & Form1.DataGridView1(3, i).Value.ToString
        End If
        PDFName += ".pdf"

        'Generate PDF based on file type - eliminated other file types for efficiency
        If Form1.DataGridView1(2, i).Value.ToString = "Excel" Then

            WorkbookName = Form1.DataGridView1(1, i).Value.ToString
            CurrentSheet = Form1.DataGridView1(3, i).Value.ToString

            If WbOpen = False Then
                xl = New Excel.Application
                xl.Workbooks.Open(FileName:=CurrentFile, UpdateLinks:=False)
                CurrentBook = xl.ActiveWorkbook
            Else
                CurrentBook = xl.ActiveWorkbook
            End If

            CurrentBook.Sheets(CurrentSheet).ExportAsFixedFormat(0, FileName:=ReportPath & "\" & PDFName)

            If i < Form1.DataGridView1.Rows.Count - 1 Then
                If Form1.DataGridView1(1, i + 1).Value.ToString = WorkbookName Then
                    WbOpen = True
                End If
            Else
                WbOpen = False
                CurrentBook = Nothing
                xl.Workbooks(WorkbookName).Close(False)
                xl.Quit()
                ReleaseObject(xl)
            End If
        End If
    Next
    xl = Nothing
End Sub

我进行了一些调试,似乎没有正确地将CurrentBook变量重新分配给新的Excel文件,而是保留了旧文件的值。

0 个答案:

没有答案