簡體   English   中英

復制粘貼區域大小不一樣 VBA 1004 錯誤

[英]Copy Paste area is not the same size VBA 1004 Error

此代碼拋出錯誤。

ActiveSheet.Range(Cells(14, 7), Cells(NewRow, 8)).Copy
ws.Range("A1").Offset(rn, 6).PasteSpecial xlPasteValues

一直說大小不一樣。 有什么建議么?

您可以(重新)使用通用 sub 來復制值並避免復制/粘貼 --> copyRangeValues

使用通用 sub 可以避免在調整目標范圍大小時可能出現的錯誤。 如果它是正確的,那么它對所有其他調用也是正確的。

加上另一個提示:使用變量名來解釋變量包含的內容。 rn是一個無法自我解釋的變量......這可能是你錯誤的根源......

Option Explicit

Public Sub copyWhatever()

'ActiveSheet.Range(Cells(14, 7), Cells(NewRow, 8)).Copy
'ws.Range("A1").Offset(rn, 6).PasteSpecial xlPasteValues

Dim rgSource As Range
Set rgSource = ActiveSheet.Range(Cells(14, 7), Cells(NewRow, 8))

Dim cTarget As Range
Set cTarget = ws.Range("A1").Offset(rn, 6)

copyRangeValues rgSource, cTarget

End Sub


'This is the generic sub that can be re-used for all copy tasks
Public Sub copyRangeValues(rgSource As Range, cTarget As Range)
'cTarget = cell where the copied values should start = top left corner

With rgSource
    cTarget.Resize(.Rows.Count, .Columns.Count).Value2 = .Value2
End With

End Sub

使用Range object 的Value屬性粘貼值。

引用“源”范圍並確保“目標”范圍具有相同的行數和列數

With ActiveSheet.Range(Cells(14, 7), Cells(NewRow, 8))
    ws.Range("A1").Offset(rn, 6).Resize(.Rows.Count, .columns.Count).Value = .Value
End With

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM