0

次のコードを使用して、複数の Excel ファイルからデータを取得し、それらを 1 つの新しいファイルに貼り付けています。

    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

ただし、コードを実行すると、次のエラーがスローされます。

ComException

「クラス範囲のメソッド PasteSpecial が失敗しました」

ウィッチは次の行を指しています:

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

これを解決する方法がわかりません。これはかなり一般的なエラーであるため、グーグルで調べてもほとんど答えがありません。

4

1 に答える 1