0

I am using the following code to get data from several excel files and paste them into a single new file:

    For i = 0 To amountOfFiles - 1

        Dim xlAppSource As New Excel.Application
        Dim xlAppTarget As New Excel.Application
        Dim xlWbSource As Excel.Workbook
        Dim xlWbTarget As Excel.Workbook
        Dim xlsheetSource As Excel.Worksheet
        Dim xlsheetTarget As Excel.Worksheet

        Dim CurrentFile As String = strFileNames(i)
        Dim IntAmountOfRows As Integer = amountOfRows(CurrentFile)
        Dim intStartOfEmptyRow As Int16 = amountOfRows(SummaryLocation)

        'Set current workbook
        xlWbSource = xlAppSource.Workbooks.Open(CurrentFile)
        xlWbTarget = xlAppTarget.Workbooks.Open(SummaryLocation)

        'set current worksheet
        xlsheetSource = xlWbSource.ActiveSheet
        xlsheetTarget = xlWbTarget.ActiveSheet

        'copy range of data from source to target file
        xlsheetSource.Range("A2:k" & IntAmountOfRows).Copy()
        xlsheetTarget.Range("A2:k" & intStartOfEmptyRow).PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, False, False)

        'Set focus on Summary ExcelSheet
        xlWbTarget = xlAppSource.Workbooks.Open(SummaryLocation)
        xlsheetSource = xlWbTarget.ActiveSheet

        'close excel
        xlWbSource.Close(True)
        xlWbTarget.Close(True)
        xlAppSource.Quit()
        xlAppTarget.Quit()

        'Cleanup
        xlAppSource = Nothing
        xlAppTarget = Nothing
        xlWbSource = Nothing
        xlWbTarget = Nothing
        xlsheetSource = Nothing
        xlsheetTarget = Nothing

    Next

However, when I execute the code, it throws the following error:

ComException

"Method PasteSpecial of Class Range has failed"

Wich points to the line:

xlsheetTarget.Range("A2:k" & intStartOfEmptyRow).PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, False, False)

I have no idea how to solve this, seeing as its a pretty general Error, googling it gives me next to none answers.

4

1 回答 1

1

I have found a way that does what I want, however I don't know WHY. So I will not accept my own answer, but wait for someone to explain it.

the code I used now is:

'copy range of data from source to target file
xlsheetSource.Range("A2:k" & IntAmountOfRows).Copy()
xlsheetTarget.Range("A" & intStartOfEmptyRow).PasteSpecial(Excel.XlPasteType.xlPasteValues)
于 2013-10-07T08:41:05.843 回答