2017-08-05 193 views
-1

我在工作簿1中有一個Excel工作表,我想根據當天(星期日,星期一...)使用VBA複製該工作表中的數據行,但要另一本工作日(天)每天有一個單獨的工作表。從工作簿1中的工作表複製到工作簿2中的多個工作表

所有我發現從一個工作簿被複制到只有一張的另一個工作簿

能否請你幫我這個例子?

我使用這個代碼,但是當我試圖重複的其他日子裏,我感到困惑,尤其是當使用開放&保存方法

Sub myTest() 
Dim LastRow As Integer, i As Integer, erow As Integer 
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 

For i = 2 To LastRow 

If Cells(i, 2).Value = "Sunday" Then 

Range(Cells(i, 1), Cells(i, 7)).Select 
Selection.Copy 
Workbooks.Open Filename:="C:\Users\User1\Documents\Days.xlsx" 
Worksheets("Sunday").Select 
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 
ActiveSheet.Cells(erow, 1).Select 
ActiveSheet.Paste 
ActiveWorkbook.Save 
ActiveWorkbook.Close 
Application.CutCopyMode = False 
End If 
Next i 
End Sub 
+0

看一看這個:https://stackoverflow.com/questions/19351832/copy-from-one-workbook-and-paste-into-another,然後告訴我們你嘗試過什麼。 –

+0

[複製一個工作簿並粘貼到另一個]可能的重複(https://stackoverflow.com/questions/19351832/copy-from-one-workbook-and-paste-into-another) – ChrisM

回答

2

只是在添加更多天。 下面的代碼也將增加在週一,做同樣爲一週的休息

Sub myTest() 
Dim LastRow As Integer, i As Integer, erow As Integer 
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 

For i = 2 To LastRow 

If Cells(i, 2).Value = "Sunday" Then 

Range(Cells(i, 1), Cells(i, 7)).Select 
Selection.Copy 
Workbooks.Open Filename:="C:\Users\User1\Documents\Days.xlsx" 
Worksheets("Sunday").Select 
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 
ActiveSheet.Cells(erow, 1).Select 
ActiveSheet.Paste 
ActiveWorkbook.Save 
ActiveWorkbook.Close 
Application.CutCopyMode = False 
End If 

If Cells(i, 2).Value = "Monday" Then 

Range(Cells(i, 1), Cells(i, 7)).Select 
Selection.Copy 
Workbooks.Open Filename:="C:\Users\User1\Documents\Days.xlsx" 
Worksheets("Monday").Select 
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 
ActiveSheet.Cells(erow, 1).Select 
ActiveSheet.Paste 
ActiveWorkbook.Save 
ActiveWorkbook.Close 
Application.CutCopyMode = False 
End If 

Next i 
End Sub 

你也可以只打開其他工作簿一次,提高工作效率之後只保存它。

+0

您可能還希望在For i = 2之前移動** Workbooks.Open **並在Next i後保存並關閉 – ChrisM

1

如果你的代碼正在尋找只複製到另一個然後你可以重複其他日子的代碼。

+0

我試過,但我沒有知道我是否每次都必須使用open方法或何時應該保存 – simpatico

+0

查看您現在添加到問題中的代碼是否僅將週日行添加到星期日表中? – ChrisM

+0

是所有匹配星期日的條件都複製到另一個工作簿中名爲Sunday的工作表中,並且我希望在整個星期內完成 – simpatico

3

如果你不想打開和關閉另一個工作簿,那麼下面的代碼可能會更好。

Sub myTest() 
Dim LastRow As Integer, i As Integer, erow As Integer, Dayname As String 

Workbooks.Open Filename:="C:\Users\User1\Documents\Days.xlsx" 
ThisWorkbook.Activate 
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 

For i = 2 To LastRow 
ThisWorkbook.Activate 
Set DayName = Cells(i, 2).Value 

Range(Cells(i, 1), Cells(i, 7)).Select 
Selection.Copy 
Windows("Days.xlsx").Activate 
Worksheets(DayName).Select 
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row 
ActiveSheet.Cells(erow, 1).Select 
ActiveSheet.Paste 

Next i 
End Sub 
相關問題