我使用以下代码从多个excel文件中获取数据并将其粘贴到一个新文件中:
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
但是,当我执行代码时,它会抛出以下错误:
“方法类别范围的PasteSpecial已失败”
Wich指向这条线:
xlsheetTarget.Range("A2:k" & intStartOfEmptyRow).PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, False, False)
我不知道如何解决这个问题,因为它是一个相当普遍的错误,谷歌搜索它几乎没有答案。
答案 0 :(得分:1)
我找到了一种方法可以做我想要的,但我不知道为什么。所以我不会接受我自己的答案,而是等待某人解释。
我现在使用的代码是:
'copy range of data from source to target file
xlsheetSource.Range("A2:k" & IntAmountOfRows).Copy()
xlsheetTarget.Range("A" & intStartOfEmptyRow).PasteSpecial(Excel.XlPasteType.xlPasteValues)