Excel复制(目的地:=)在VB.NET中失败

问题描述 投票:0回答:1

我正在使用copy(Destination:=),想将一个Excel中的整个记录​​复制到另一个Excel文件中,但是执行失败。是否因为需要使用范围?因为没有必要使用范围,因为我想复制所有内容并粘贴到另一个Excel文件中]

oWorkBook.Sheets(1).Cells.Copy(Destination:=oWorkBookOri.Sheets(1).Range("A" & oWorkBookOri.Sheets(1).UsedRange.SpecialCells(XlCellType.xlCellTypeLastCell).Row + 1))

它提到了如下错误。

“ Range类的复制方法失败。

我以前的代码如下

oWorkBook.Sheets(1).Cells.Copy()
oWorkBookOri.Sheets(1).Range("A" & oWorkBookOri.Sheets(1).UsedRange.SpecialCells(XlCellType.xlCellTypeLastCell).Row + 1).Select()
oWorkBookOri.Sheets(1).Paste

并且它一直发生错误消息“ System.Runtime.InteropServices.COMException(0x800A03EC):Worksheet类的粘贴方法失败”,尽管如此,我还是更改为复制目标语法并如上所述发生错误。

excel vb.net excel-interop
1个回答
0
投票

如果您使用.Cells.Copy()(即工作表中的每个单元格,则目标位置必须为Range(“ A1”),否则复制的单元格没有足够的空间。我假设您只想复制使用过的行,在这种情况下,请尝试

Dim rngSource As Range, rngTarget As Range, targetRow As Long

rngSource = oWorkbook.Sheets(1).UsedRange
With oWorkbookOri.Sheets(1)
    targetRow = .UsedRange.SpecialCells(XlCellType.xlCellTypeLastCell).Row + 1
    rngTarget = .cells(targetRow, rngSource.Column)
End With

rngSource.Copy(rngTarget)
MsgBox("Copied " & rngSource.Address & " to " & rngTarget.Address, vbInformation)
© www.soinside.com 2019 - 2024. All rights reserved.