2016-12-05 44 views
0

我對VBA非常陌生,並且很難使代碼正常工作。我知道這裏有很多類似的問題,但是我找不到合適的粘貼配方。我需要複製工作表「Workbook1」中的數據,並將其粘貼到「Workbook2」工作表的下一個可用行中,並進行調換。感謝您的幫助。將數據從一個工作表複製到第一個可用行和轉置處的數據

到目前爲止我有:

Sub MoveData() 

'Define variables 
Dim Workbook1 As Workbook 
Dim Workbook2 As Workbook 
Dim wb As Workbook 
Dim ws As Worksheet 

Dim LastRow As Long 

'Set and Open 
Set wb = ThisWorkbook 
Set ws = wb.Worksheets("Sheet1") 

LastRow = ws.Range("A" & Rows.Count).End(xlUp).Offset(1).Row 

'Copy and paste 
wb.ws.Range("A1:A5").Copy 
Set Workbook2 = Workbooks.Open("H:\Macro\Workbook2") 
Workbook2.Sheets("Sheet1").Range("A1:M & LastRow").PasteSpecial Transpose:=True 

End Sub 
+0

我嘗試下面的代碼,我一個,直到最後一行復制範圍中的列數據,讓我知道它是否適合你 –

+0

您的代碼運行完美,非常感謝!如果您不介意,我還有一個問題:我想爲在A列中執行宏時添加一個時間戳,然後從B列開始粘貼數據(我簡單地將粘貼目標更改爲單元格B,所以這部分是好的)。你知道如何做到這一點?再次感謝!! – Caras

+0

「時間戳」是什麼意思?你想複製列A並粘貼到列B並轉置? –

回答

0

下面的代碼在ThisWorkbook查找最後一排「工作表Sheet1」,複製整個範圍在列A,然後粘貼它第一個可用行的「 「Workbook2.xlsm」中的「Sheet1」。 Paste方法與PasteSpecial,僅值和移調。

Option Explicit 

Sub MoveData() 

'Define variables 
Dim Workbook1 As Workbook 
Dim Workbook2 As Workbook 
Dim wb As Workbook 
Dim ws As Worksheet 
Dim LastRow As Long, DestLastRow As Long 

' Set wb 
Set wb = ThisWorkbook 
Set ws = wb.Worksheets("Sheet1") 

' set and open Workbook2, need to add the file extenstion (.xlsm) 
Set Workbook2 = Workbooks.Open("H:\Macro\Workbook2.xlsm") 

With ws 
    ' find last row with data in Column A to copy 
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
    .Range("A1:A" & LastRow).Copy 
End With 

With Workbook2.Sheets("Sheet1") 
    ' find last row with data in destination workbook "Workbook2.xlsm" 
    DestLastRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1).Row 
    ' paste special only values, and transpose 
    .Range("A" & DestLastRow).PasteSpecial xlValues, Transpose:=True 
End With 

End Sub 
相關問題