Link to home
Start Free TrialLog in
Avatar of Gazza83
Gazza83

asked on

VB Code

Basically I was planning to hide sheet3 on my workbook, but when the command button is clicked on sheet1; the hidden sheet (sheet 3) would open in a brand new/separate worksheet.

So I was thinking the code could copy the format in the hidden sheet (sheet3) and then paste this into a brand new occurence of excel.
Avatar of SiddharthRout
SiddharthRout
Flag of India image

Try this simple code

Private Sub CommandButton1_Click()
    Dim wb1 As Workbook, wb2 As Workbook
    
    Set wb1 = ActiveWorkbook
    Set wb2 = Workbooks.Add
    
    wb1.Sheets("Sheet3").Copy After:=wb2.Sheets(wb2.Sheets.Count)
    wb2.Sheets(wb2.Sheets.Count).Visible = True
End Sub

Open in new window


Sid
Avatar of Gazza83
Gazza83

ASKER

in excel 2011 it is creating the new file but as opposed to just sheet 3 being in the new workbook, there are now four sheets within the new workbook "Sheet3 (2)", sheet3,sheet2, sheet1

Try this

Private Sub CommandButton1_Click()
    Dim wb1 As Workbook, wb2 As Workbook
    
    Set wb1 = ActiveWorkbook
    Set wb2 = Workbooks.Add
    
    For i = 1 To wb2.Sheets.Count
        Sheets(i).Name = "Sid" & i
    Next
    
    wb1.Sheets("Sheet3").Copy After:=wb2.Sheets(wb2.Sheets.Count)
    wb2.Sheets(wb2.Sheets.Count).Visible = True
    
    For i = wb2.Sheets.Count To 1 Step -1
        Application.DisplayAlerts = False
        On Error Resume Next
        If InStr(1, Sheets(i).Name, "sid", vbTextCompare) Then Sheets(i).Delete
        On Error GoTo 0
        Application.DisplayAlerts = True
    Next
    
    wb2.Sheets(1).Name = "Sheet3"
End Sub

Open in new window


Sid
ASKER CERTIFIED SOLUTION
Avatar of SiddharthRout
SiddharthRout
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gazza83

ASKER

Brilliant, thanks!
Glad to be of help. Though it worked, but I saw a small error in the above code.

Please change line 8

Sheets(i).Name = "Sid" & i

to

wb2.Sheets(i).Name = "Sid" & i

and line 18

        If InStr(1, Sheets(i).Name, "sid", vbTextCompare) Then Sheets(i).Delete

to

        If InStr(1, wb2.Sheets(i).Name, "sid", vbTextCompare) Then wb2.Sheets(i).Delete


Sid