[英]Copy rows until the last row with value ONLY to another workbook
我能夠使用預定義的范圍將行復制到另一個工作簿。 但是,我想確保它只需要復制帶有值的那些。 我一直在制定這段代碼,但它返回錯誤-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僅使用值修復我的副本行,但粘貼錯誤仍然存在
您可以迭代單個單元格並僅復制具有值的單元格:
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
嘗試定義需要復制的最終列,然后定義范圍中的開始和結束單元格:
FinalCol = 23 '(or whatever you need)
getDBsht.Range(getDBsht.Cells(1, 1), getDBsht.Cells(FinalRow, FinalCol)).Copy
另請注意,上面我指定了范圍中的單元格來自哪個工作表。 如果您同時打開多個工作簿/工作表,這可以提供幫助。
在開始復制之前定義目的地也是一個好主意。
CopyTo = ThisWorkbook.Sheets("ConTracker_DB").Range("A1")
回答我的問題:))
基本上如果你使用usedRange.Copy
你應該用Cells(1, 1).PasteSpecial Paste:=xlPasteValues
粘貼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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.