简体   繁体   中英

Move an Excel Work Sheet to Another existing workbook with different sheet name as new sheet

I am trying to create a Vb Script to Copy/Move an Excel worksheet to another workbook as new sheet ('X' is the source workbook 'xsheet' (the sheetname should be a parameter) is the sheet name which I want to copy to another workbook called 'Y' As new sheet with name 'ysheet'(the sheetname should be a parameter)

NB: The Source workbook and Destination workbook have multiple sheets.

The below code will work only if the source workbook have only one sheet.

Set objExcel1 = CreateObject("Excel.Application")
Set objExcel = CreateObject("Excel.Application")

Set objWorkbook = objExcel1.Workbooks.Open("C:\Users\x\test.xlsx")
Set objWorkbook1 = objExcel.Workbooks.Open("C:\Users\x\test1.xlsx")
objExcel.Visible = TRUE

Set objLastSheet = objWorkbook.Worksheets(1)

Set objWorksheet = objWorkbook1.Worksheets("Sheet1")

objWorksheet.Copy, objLastSheet
Set objWorksheet = objWorkbook.Worksheets("ff")

Ignoring the obvious errors in your code, here is a working example with some background info.

Option Explicit

Dim xl : Set xl = CreateObject("Excel.Application") 'start Excel
Dim wb1: Set wb1 = xl.Workbooks.Open("E:\Temp\Book1.xlsx") 'open source workbook
Dim wb2: Set wb2 = xl.Workbooks.Open("E:\Temp\Book2.xlsx") 'open target workbook

'Copy the worksheet in wb1 to the end of the sheets in wb2
'The Copy method expects Copy(before, after),
'and 'before' and 'after' are mutually exclusive
'so pass Null for the one you don't want 
'(it defaults to Before)

'I will admit that it isn't immediately obvious from documentation that
'you can actually copy to other workbooks
wb1.Sheets("SheetToCopy").Copy Null, wb2.Sheets(wb2.Sheets.Count)
'Rename it as you like afterwards
wb2.Save()
wb1.Close()
wb2.Close()
xl.Quit()
Set xl = Nothing
WScript.Quit 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM