创建一个工作簿,然后从另一个工作簿添加工作表

时间:2019-12-04 09:35:23

标签: excel vba copy add spreadsheet

我需要一个VBA代码,该代码可以创建具有确定路径,名称和格式的excel文件,因此我编写了以下几行代码:

Sub Parametrage()
'This is the workbook i need to copy sheets from , i chose to store those sheets in variable because i may need them later 
Workbooks.Open "C:\Users\Oumayna EL JAHRANI\Desktop\Test\Fichier Type.xlsx"
Dim ClasseurType As Workbook: Set ClasseurType = ActiveWorkbook
Dim Display As Worksheet: Set Publié = ClasseurType.Worksheets("Publié")
Dim Ajustements As Worksheet: Set Ajustement = ClasseurType.Worksheets("Ajustement")
Dim Variables As Worksheet: Set Variables = ClasseurType.Worksheets("Variables")
Dim Database As Worksheet: Set Source = ClasseurType.Worksheets("Source")
'Here starts the creation of the new file 
Dim CibleApp As New Excel.Application
Dim CibleClasseur As Workbook
Set CibleClasseur = CibleApp.Workbooks.Add
 With CibleClasseur
 .Title = "Classeur Cible"
 .Subject = "Cible"
 .SaveAs Filename:="C:\Users\Oumayna EL JAHRANI\Desktop\Test\ObjetCible.xlsx"
 End With
'Here i add the sheets i want to my new workbook and this is the part i can't get to execute 
Sheets(Publié).Copy Before:=Workbooks(CibleClasseur).Sheets(1)
Sheets(Ajustement).Copy Before:=Workbooks(CibleClasseur).Sheets(2)
Sheets(Variables).Copy Before:=Workbooks(CibleClasseur).Sheets(3)
Sheets(Source).Copy Before:=Workbooks(CibleClasseur).Sheets(5)
Workbooks(ClasseurType).Close savechanges:=True
Application.Quit
End Sub 

此代码中有两个问题,首先,当我执行它时,它在第16行停止,第二个问题是,由于每次我第二次执行时,它都会创建一个xlsx文件,所以我在该行上有一个错误我保存新文件的位置,之后我无法删除旧文件。我希望首先能够执行整个代码,并且能够在代码停止时删除文件并关闭应用程序。

1 个答案:

答案 0 :(得分:0)

我相信您的代码应如下所示:

Sub Parametrage()
'This is the workbook i need to copy sheets from , i chose to store those sheets in variable because i may need them later

Dim ClasseurType As Workbook: Set ClasseurType = Workbooks.Open("C:\Users\Oumayna EL JAHRANI\Desktop\Test\Fichier Type.xlsx")
Dim Publié As Worksheet: Set Publié = ClasseurType.Worksheets("Publié")
Dim Ajustement As Worksheet: Set Ajustement = ClasseurType.Worksheets("Ajustement")
Dim Variables As Worksheet: Set Variables = ClasseurType.Worksheets("Variables")
Dim Source As Worksheet: Set Source = ClasseurType.Worksheets("Source")
'Here starts the creation of the new file
Dim CibleClasseur As Workbook
Set CibleClasseur = Workbooks.Add
 With CibleClasseur
 .Title = "Classeur Cible"
 .Subject = "Cible"
 .SaveAs Filename:="C:\Users\Oumayna EL JAHRANI\Desktop\Test\ObjetCible.xlsx"
 End With
'Here i add the sheets i want to my new workbook and this is the part i can't get to execute
Publié.Copy Before:=CibleClasseur.Sheets(1)
Ajustement.Copy Before:=CibleClasseur.Sheets(2)
Variables.Copy Before:=CibleClasseur.Sheets(3)
Source.Copy Before:=CibleClasseur.Sheets(5)
ClasseurType.Close savechanges:=True

End Sub

我不清楚您打算最后关闭哪个工作簿。