将行复制到最后一行,其值仅为另一个工作簿

时间:2016-04-25 12:36:00

标签: excel vba excel-vba

我可以使用预定义的范围将行复制到另一个工作簿。但是,我想确保它只需要复制带有值的那些。我一直在制定这段代码,但它返回错误-1004

Private Sub test()

Dim WBa As Workbook, MyPathA As String
Dim FinalRow As Long
Dim getDBsht As Worksheet

MyPathA = "sharepoint.com/Financial Tracker v8.xlsx"  

ThisWorkbook.Sheets("ConTracker_DB").UsedRange.ClearContents

' Attempt to open a sharepoint file
Set WBa = Workbooks.Open(MyPathA)
'Set WBb = Workbooks.Open(MyPathB)

Set getDBsht = WBa.Sheets("ConTracker_DB")
getDBsht.UsedRange.Copy

'error starts here
ThisWorkbook.Sheets("ConTracker_DB").UsedRange.Paste


Application.CutCopyMode = False
WBa.Close

Set WBa = Nothing

End Sub

更新后的代码: UsedRange仅使用值修复了我的副本行,但仍然存在粘贴错误

3 个答案:

答案 0 :(得分:0)

您可以迭代各个单元格并仅复制具有值的那些:

Dim sourceCell as Range
Dim targetCell as Range
Set targetCell = ThisWorkbook.Sheets("ConTracker_DB").Range("A1").
For each sourceCell in Range("theNamedRangeYouWantToCopyFrom")
'I'm not sure if you need a dynamic range to copy from, but if you don't...
'...it's much easier to use a "named range" for that.
  If sourceCell.Value <> "" Then
    targetCell.Value = sourceCell.Value
    Set targetCell = targetCell.Offset(1,0)
  End If
Next sourceCell 

答案 1 :(得分:0)

尝试定义您需要复制的最终列,然后定义范围内的开始和结束单元格:

FinalCol = 23  '(or whatever you need)
getDBsht.Range(getDBsht.Cells(1, 1), getDBsht.Cells(FinalRow, FinalCol)).Copy

另请注意,上面我指定了范围中的单元格来自哪个工作表。如果您同时打开多个工作簿/工作表,这可能会有所帮助。

在开始复制之前定义目的地也是一个好主意。

CopyTo = ThisWorkbook.Sheets("ConTracker_DB").Range("A1")

答案 2 :(得分:0)

回答我的问题:))

基本上,如果您正在使用usedRange.Copy

你应该粘贴 Cells(1, 1).PasteSpecial Paste:=xlPasteValues

如果你正在使用它,请在下面找到完整的代码:

Private Sub test()

Dim WBa As Workbook, MyPathA As String
Dim FinalRow As Long
Dim getDBsht As Worksheet

MyPathA = "sharepoint.com/Financial Tracker v8.xlsx"  

ThisWorkbook.Sheets("ConTracker_DB").UsedRange.ClearContents

' Attempt to open a sharepoint file
Set WBa = Workbooks.Open(MyPathA)
'Set WBb = Workbooks.Open(MyPathB)

Set getDBsht = WBa.Sheets("ConTracker_DB")
getDBsht.UsedRange.Copy


ThisWorkbook.Sheets("ConTracker_DB").Cells(1, 1).PasteSpecial Paste:=xlPasteValues


Application.CutCopyMode = False
WBa.Close

Set WBa = Nothing

End Sub