2014-03-03 38 views
-2

我在一张纸上有一列行数未知的行,我想复制它并粘贴在另一张纸上。至于行数未知,我把它定义为一个变量:如何将VBA中的一列粘贴到另一张纸上?

Sub Official() 
Dim lastrow As Long 
Dim LastCol As Long 
Set currentsheet = ActiveWorkbook.Sheets(1) 

LastRow = Range("A65536").End(xlUp).Row 
LastCol = Range("A1").End(xlToRight).Column 

Sheets("Type_1").Range("D8" & "D" & LastRow).Copy 
Sheets(1).Range("A2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
      :=False, Transpose:=True 
End Sub 

我得到这个宏的错误,也许有人可以帮助我吗?

+2

你已经错过了结肠癌。将'Range(“D8”&“D”&LastRow).Copy'更改为'Range(“D8:D”&LastRow).Copy'。顺便说一句,在代码'lastrow'中定义*活动工作表*,而您从工作表'Type_1'中复制数据。这是正确的行为吗? –

+0

谢谢!我改变了,但现在不复制任何东西。这可能是LastRow变量定义的问题吗? 我应该为Type_1定义它。问题是我必须复制许多不同的工作表的列,我必须为他们每个人定义lastrow? – Ale

+3

在代码'lastrow'中定义了*活动工作表*,而您从工作表'Type_1'中复制数据。尝试使用'LastRow = Sheets(“Type_1”)。Range(“A65536”)。End(xlUp).Row' –

回答

0

你可以尝试:

Sub Official() 
Dim lastrow As Long 
Dim LastCol As Long 
Dim srcLastRow As Long 

    Set currentsheet = ActiveWorkbook.Sheets(1) 

    ' handle Office 2007+ with more than 65536 rows... 
    lastrow = Range("A" & currentsheet.Rows.Count).End(xlUp).Row 
    LastCol = Range("A1").End(xlToRight).Column 

    ' find out how many rows there are in the source sheet 
    srcLastRow = Sheets("Type_1").Range("D" & Sheets("Type_1").Rows.Count).End(xlUp).Row 

    ' copy from the course sheet to the currentSheet in the range specified 
    Sheets("Type_1").Range("D8:" & "D" & srcLastRow).Copy Destination:=currentsheet.Range("A" & lastrow) 

    ' or maybe you want: 
    ' Sheets("Type_1").Range("D8:" & "D" & srcLastRow).Copy Destination:=currentsheet.Cells(lastrow, LastCol) 

End Sub 
+0

谢谢,菲利普,它已经解决了,但我认为你的解决方案也能正常工作! – Ale

相关问题