2017-10-12 95 views
0

我試圖在不使用剪貼板的情況下將值粘貼到不同工作表上的動態範圍。當代碼到達Range = Range部分時,它會錯誤地指出「應用程序定義或對象定義的錯誤」。有任何想法嗎?複製到沒有剪貼板的動態範圍

Sub Test2() 
Dim Start As Worksheet 
Dim ED As Worksheet 
Dim r As Integer, c As Integer, r1 As Integer, c1 As Integer 

Set Start = Sheets("Start") 
Set ED = Sheets("End") 

r = 1 
c = ActiveSheet.UsedRange.Columns.Count 



With Start 
    Do Until .Cells(r, c).Value = "" 
     r = r + 1 

    Loop 
    r = r - 1 

End With 
r1 = 1 
c1 = ActiveSheet.UsedRange.Columns.Count 

With ED 

    Do Until .Cells(r1, c1).Value = "" 
     r1 = r1 + 1 

    Loop 
    r1 = r1 

Range(Cells(r1, 1), Cells(r1 + r - 1, c1)) = Start.Range(Cells(r, c), Cells(1, 1)) 

Start.Activate 
+1

'.Range(.Cells(R1,1),.Cells(R1 + R1,C1))值= Start.Range(Start.Cells(R ,c),Start.Cells(1,1))。Value' Qualify *** EVERY *** Range object with its parent sheet。 –

回答

3
  1. ALWAYS每一個家長有資格每Range對象。該範圍()內的Cells()需要在同一母公司必須指出:

Start.Range(Start.Cells(r, c), Start.Cells(1, 1))

  • 我們不需要循環,而且可以使用END()來找到最後的列和行。
  • 替換:

    Do Until .Cells(r, c).Value = "" 
        r = r + 1 
    
    Loop 
    r = r - 1 
    

    隨着:

    c = .Cells(1, .Columns.Count).End(xlToLeft).Column 
    r = .Cells(.Rows.Count, c).End(xlUp).Row 
    
  • 使用調整大小,它是較短的,更易於維護:
  • .Cells(r1+1, 1).Resize(r, c).Value = Start.Cells(1, 1).Resize(r, c).Value

    所以:

    Sub Test2() 
    Dim Start As Worksheet 
    Dim ED As Worksheet 
    Dim r As Long, c As Long, r1 As Long, c1 As Long 
    
    Set Start = Sheets("Start") 
    Set ED = Sheets("End") 
    
    With Start 
        c = .Cells(1, .Columns.Count).End(xlToLeft).Column 
        r = .Cells(.Rows.Count, c).End(xlUp).Row 
    End With 
    With ED 
        c1 = .Cells(1, .Columns.Count).End(xlToLeft).Column 
        r1 = .Cells(.Rows.Count, c1).End(xlUp).Row 
        .Cells(r1+1, 1).Resize(r, c).Value = Start.Cells(1, 1).Resize(r, c).Value 
    End With 
    
    +0

    成功!我知道這是一個小細節。感謝幫助/反饋! – Zach