简体   繁体   中英

How to VBA to select a pair of sheets and copy them to a new wb?

'First-timer here, so thanks for your patience!
I have a workbook with multiple sheets, and I need to:

1)Select pairs of worksheets (index and index +1)

2)Copy them into a new workbook

3)Rename the sheets with whatever label is in a referenced cell (such as A1)

4)Then repeat for every pair of sheets in the workbook (dozens of pairs)

Since I am very new to vba (only took one class), I am easily confused. The only part I have so far is referencing cell A1 to rename the sheet to whatever text string is in that cell. I can't figure out the rest of it. I'm thinking it has something to do with worksheet.index or worksheets(index) and some kind of loop where index adds 2 and activates that sheet and the next one before copying: sheets 1 and 2, then sheets 3 and 4, etc.

Private Sub Worksheet_Calculate() 
 Dim s As String 
 s = "sheet 1" 
 If Range("A1").Value <> "" Then 
     s = Range("A1").Value 
 End If 
 ActiveSheet.Name = s 
 End Sub 

The way I understand it, cell A1 has to be checked to be sure it's not null because you can't name a sheet with a null value. The usage and syntax on the rest of it is quite beyond me at this point, but I really want to learn and eventually become a contributing member of this community. I'm brand new at my job and only working part-time, so bringing a solution to my boss might mean me becoming permanent. Therefore, a BIG, BIG THANKS!!!

Option Explicit

Private Sub Worksheet_Calculate()
Dim s As String
Dim ws As Worksheet
Dim wsi As Worksheet

Set wsi = Sheets("Sheet4")' You need to create a name for the sheet to paste into

For Each ws In ActiveWorkbook.Worksheets
If Not IsEmpty(ws.Range("A1")) and ws.name = "INDEXCOPY" Then
     ws.Name = ws.Range("A1").Value
     ws.Range("A1:" & ws.Range("A1").SpecialCells(xlCellTypeLastCell).Address).Copy _
     Destination:=wsi.Range("A1")
End If
Next ws
End Sub

This code will get you started, however, you need a way to distinguish between an index sheet you want to copy from, versus an index sheet you want to copy to. You would need to add an additional if then statement, see comment above. I would look here - http://www.rondebruin.nl/win/s3/win006.htm

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